#!/usr/bin/env python3
"""Contract checks for CARBON's project-first onboarding and durable workspace state."""

from __future__ import annotations

import json
import subprocess
import tempfile
from pathlib import Path


PLUGIN_ROOT = Path(__file__).resolve().parents[1]
SCRIPT = PLUGIN_ROOT / "runtime" / "carbon" / "scripts" / "carbon_workspace.py"


def run(*args: str, ok: bool = True) -> tuple[int, dict]:
    result = subprocess.run(
        ["python3", str(SCRIPT), *args],
        cwd=PLUGIN_ROOT,
        text=True,
        capture_output=True,
        check=False,
    )
    if ok and result.returncode != 0:
        raise AssertionError(result.stderr or result.stdout)
    if not ok and result.returncode == 0:
        raise AssertionError("Expected command to fail")
    stream = result.stdout if result.returncode == 0 else result.stderr
    return result.returncode, json.loads(stream)


def main() -> int:
    with tempfile.TemporaryDirectory(prefix="carbon-workspace-contract-") as temporary:
        root = (Path(temporary) / "project").resolve()
        (root / "src").mkdir(parents=True)
        (root / "tests").mkdir()
        (root / "package.json").write_text(
            '{"scripts":{"test":"node --test"},"dependencies":{"express":"latest"}}\n',
            encoding="utf-8",
        )
        (root / "src" / "app.js").write_text("export const app = true;\n", encoding="utf-8")
        (root / "tests" / "app.test.js").write_text("// representative test\n", encoding="utf-8")

        _, inspection = run("inspect", "--root", str(root), "--max-files", "500")
        assert inspection["firstRun"] is True
        assert inspection["needsFocusChoice"] is True
        assert inspection["stateDirectory"] == str(root / ".carbon")
        assert not (root / ".carbon").exists(), "Read-only inspection created project state"
        assert len(inspection["progress"]) >= 4
        assert any(option["id"] == "whole-project" for option in inspection["focusOptions"])
        assert "imitating" in inspection["professionalJudgment"]["identityBoundary"]
        assert inspection["professionalJudgment"]["schema"] == "carbon.testing-doctrine/v1"
        assert inspection["professionalJudgment"]["practiceBalances"]
        assert any(
            row["id"] == "rapid-and-session-based-exploration"
            and row["pro"] and row["con"] and row["carbonDefault"]
            for row in inspection["professionalJudgment"]["practiceBalances"]
        )

        _, missing_focus = run("init", "--root", str(root), ok=False)
        assert "Choose a focus" in missing_focus["error"]
        assert not (root / ".carbon").exists()

        _, initialized = run(
            "init", "--root", str(root), "--focus", "checkout reliability",
            "--proactivity", "proactive", "--max-files", "500",
        )
        assert initialized["onboardingComplete"] is True
        assert initialized["currentPreferences"]["focus"] == "checkout reliability"
        assert initialized["currentPreferences"]["proactivity"] == "proactive"
        for relative in (
            "workspace/profile.json", "workspace/preferences.json", "workspace/journey.json",
            "workspace/events.jsonl", "framework/coverage.json", "tests/intent-tests.json",
            "runs", "learning", "recordings", "auto", "browser/sessions",
        ):
            assert (root / ".carbon" / relative).exists(), relative
        intent_library = root / ".carbon" / "tests" / "intent-tests.json"
        assert json.loads(intent_library.read_text(encoding="utf-8"))["schema"] == "carbon.intent-library/v1"

        intent_library.write_text(json.dumps({
            "schema": "carbon.intent-tests/v1",
            "tests": [{"id": "LEGACY-001"}],
            "updatedAt": None,
        }), encoding="utf-8")
        run(
            "init", "--root", str(root), "--focus", "checkout reliability",
            "--proactivity", "proactive", "--max-files", "500",
        )
        migrated = json.loads(intent_library.read_text(encoding="utf-8"))
        backup = intent_library.with_name("intent-tests.pre-migration-carbon.intent-tests-v1.json")
        assert migrated["schema"] == "carbon.intent-library/v1"
        assert migrated["tests"][0]["id"] == "LEGACY-001"
        assert json.loads(backup.read_text(encoding="utf-8"))["schema"] == "carbon.intent-tests/v1"

        _, recorded = run("record", "--root", str(root), "--command", "$carbon-browser test checkout")
        assert recorded["recorded"] is True
        assert recorded["command"] == "carbon-browser"
        _, status = run("suggest", "--root", str(root), "--max-files", "500")
        journey = json.loads((root / ".carbon" / "workspace" / "journey.json").read_text(encoding="utf-8"))
        assert journey["commands"]["carbon-browser"]["count"] == 1
        assert status["firstRun"] is False
        assert status["stateIsProjectDiscoverable"] is True

        destination = (Path(temporary) / "external-state").resolve()
        _, rejected = run(
            "relocate", "--root", str(root), "--destination", str(destination), ok=False,
        )
        assert "confirm" in rejected["error"]
        _, moved = run(
            "relocate", "--root", str(root), "--destination", str(destination), "--confirm",
            "--max-files", "500",
        )
        assert moved["relocated"] is True
        assert moved["stateIsProjectLocal"] is False
        assert moved["stateIsProjectDiscoverable"] is True
        assert (root / ".carbon").is_symlink()
        assert (root / ".carbon").resolve() == destination / ".carbon"
        _, external_status = run("status", "--root", str(root), "--max-files", "500")
        assert external_status["stateDirectory"] == str(destination / ".carbon")
        assert external_status["currentPreferences"]["focus"] == "checkout reliability"

        _, nested_rejected = run(
            "relocate", "--root", str(root),
            "--destination", str(destination / ".carbon" / "nested"), "--confirm", ok=False,
        )
        assert "inside the current" in nested_rejected["error"]
        _, returned = run(
            "relocate", "--root", str(root), "--destination", str(root), "--confirm",
            "--max-files", "500",
        )
        assert returned["relocated"] is True
        assert returned["stateIsProjectLocal"] is True
        assert (root / ".carbon").is_dir() and not (root / ".carbon").is_symlink()
        assert not (destination / ".carbon").exists()

    print("PASS: project-first inspection, focus, durable stash, journey, suggestions, and relocation verified.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
