#!/usr/bin/env python3
"""Contract test for CARBON's safe, live pre-run execution-plan snapshot."""

from __future__ import annotations

import datetime as dt
import json
import os
import subprocess
import tempfile
import time
import urllib.error
import urllib.request
from pathlib import Path


PLUGIN = Path(__file__).resolve().parents[1]
RUNTIME = PLUGIN / "bin" / "carbon-runtime"


def call(*args: str, ok: bool = True) -> subprocess.CompletedProcess[str]:
    result = subprocess.run([str(RUNTIME), *args], capture_output=True, text=True)
    if ok and result.returncode:
        raise AssertionError(result.stderr or result.stdout)
    if not ok and result.returncode == 0:
        raise AssertionError("Command unexpectedly succeeded")
    return result


def snap(root: Path, plan: Path, run_dir: Path | None = None) -> dict:
    args = ["plan-view", "snapshot", "--root", str(root), "--plan", str(plan)]
    if run_dir:
        args.extend(["--run-dir", str(run_dir)])
    return json.loads(call(*args).stdout)


def main() -> int:
    with tempfile.TemporaryDirectory(prefix="carbon-plan-view-") as temporary:
        root = Path(temporary)
        plan_path = root / ".carbon" / "framework" / "orchestration-plan.json"
        plan_path.parent.mkdir(parents=True)
        plan = {
            "title": "Checkout confidence pass",
            "target": "https://local.example/checkout Bearer abcdefghijklmnopqrstuvwxyz123456",
            "mode": "quick",
            "estimatedMinutes": 3,
            "scope": ["checkout", "receipt"],
            "approvalGates": ["Confirm before a paid order"],
            "stopConditions": ["Stop on unexpected production state"],
            "testStrategy": {"selected": "balanced", "rationale": "Changed checkout and adjacent receipt behavior."},
            "globalExecutionContext": {"customPrompt": "PRIVATE_CONTEXT_SHOULD_NOT_RENDER"},
            "tests": [
                {"id": "CHECKOUT-001", "title": "Successful synthetic checkout", "priority": "P0", "adapter": "static-source", "estimatedSeconds": 90, "oracle": "Checkout completes once", "oracleBasis": "checkout product promise", "predictedOutcome": "fail", "predictionBasis": "source inspection found an early return"},
                {"id": "CHECKOUT-002", "title": "Rejected invalid payment input", "priority": "P1", "adapter": "static-source", "estimatedSeconds": 90},
            ],
        }
        plan_path.write_text(json.dumps(plan), encoding="utf-8")

        ui = (PLUGIN / "ui" / "execution-plan.html").read_text(encoding="utf-8")
        assert 'location.pathname+location.search' in ui
        assert 'sessionStorage.setItem("carbon-plan-view-token",token)' in ui
        assert 'Disconnected · retrying every second' in ui

        token = "contract-local-token-" + "x" * 32
        ready_path = root / ".carbon" / "runtime" / "execution-viewer-contract.json"
        viewer_env = {**os.environ, "CARBON_PLAN_VIEW_TOKEN": token}
        viewer = subprocess.Popen(
            [str(RUNTIME), "plan-view", "serve", "--root", str(root), "--plan", str(plan_path), "--ready-file", str(ready_path), "--ttl-seconds", "120"],
            env=viewer_env,
            stdout=subprocess.DEVNULL,
            stderr=subprocess.PIPE,
            text=True,
        )
        try:
            for _ in range(50):
                if ready_path.is_file():
                    break
                if viewer.poll() is not None:
                    raise AssertionError(viewer.stderr.read() if viewer.stderr else "viewer exited early")
                time.sleep(0.1)
            assert ready_path.is_file(), "persistent viewer did not publish its ready file"
            viewer_metadata = json.loads(ready_path.read_text(encoding="utf-8"))
            assert viewer_metadata["pid"] == viewer.pid and viewer_metadata["schema"] == "carbon.execution-plan-viewer/v1"
            assert viewer_metadata["instanceId"]
            base_url = viewer_metadata["baseUrl"]
            health = json.loads(urllib.request.urlopen(f"{base_url}/health", timeout=3).read())
            assert health["instanceId"] == viewer_metadata["instanceId"] and health["pid"] == viewer.pid
            page = urllib.request.urlopen(f"{base_url}/run", timeout=3).read().decode("utf-8")
            assert "Live · updates every second" in page
            try:
                urllib.request.urlopen(f"{base_url}/api/execution-plan", timeout=3)
                raise AssertionError("persistent viewer accepted a tokenless request")
            except urllib.error.HTTPError as error:
                assert error.code == 403

            def live_snapshot() -> dict:
                request = urllib.request.Request(
                    f"{base_url}/api/execution-plan",
                    headers={"X-Carbon-Settings-Token": token},
                )
                return json.loads(urllib.request.urlopen(request, timeout=3).read())["plan"]

            served_before = live_snapshot()
            assert served_before["status"] == "planned" and served_before["progress"]["total"] == 2

            before = snap(root, Path(".carbon/framework/orchestration-plan.json"))
            serialized = json.dumps(before)
            assert before["status"] == "planned" and before["progress"]["total"] == 2
            assert before["timing"]["estimatedMinutes"] == 3 and before["timing"]["estimatedSeconds"] == 180
            assert before["approvalGates"] == ["Confirm before a paid order"]
            assert before["tests"][0]["predictedOutcome"] == "fail"
            assert before["tests"][0]["oracleBasis"] == "checkout product promise"
            assert before["qualityConfidence"]["confidenceInQuality"]["band"] == "not-assessed"
            assert before["qualityConfidence"]["remainingRisk"]["level"] == "unknown"
            assert "PRIVATE_CONTEXT_SHOULD_NOT_RENDER" not in serialized
            assert "abcdefghijklmnopqrstuvwxyz123456" not in serialized and "[REDACTED]" in before["target"]

            plan["target"] = "https://local.example/checkout"
            plan_path.write_text(json.dumps(plan), encoding="utf-8")

            run_dir = root / ".carbon" / "runs" / "plan-view-contract"
            call("run", "init", "--root", str(root), "--plan", str(plan_path), "--mode", "quick", "--run-id", "plan-view-contract")
            discovered = snap(root, plan_path)
            assert discovered["runId"] == "plan-view-contract" and discovered["status"] == "planned"

            call("run", "start", "--run-dir", str(run_dir))
            call("run", "update", "--run-dir", str(run_dir), "--test-id", "CHECKOUT-001", "--status", "running")
            call("run", "update", "--run-dir", str(run_dir), "--test-id", "CHECKOUT-001", "--status", "passed", "--actual", "Observed success")
            state_path = run_dir / "run.json"
            state = json.loads(state_path.read_text(encoding="utf-8"))
            finish = dt.datetime.now(dt.timezone.utc).replace(microsecond=0)
            state["tests"][0]["startedAt"] = (finish - dt.timedelta(seconds=60)).isoformat().replace("+00:00", "Z")
            state["tests"][0]["finishedAt"] = finish.isoformat().replace("+00:00", "Z")
            state_path.write_text(json.dumps(state), encoding="utf-8")

            running = snap(root, plan_path, run_dir)
            assert running["status"] == "running" and running["progress"]["completed"] == 1
            assert running["progress"]["percent"] == 50
            assert running["timing"]["basis"] == "observed vs planned test durations"
            assert running["timing"]["estimatedRemainingSeconds"] == 60
            assert running["qualityConfidence"]["confidenceInQuality"]["band"] == "guarded"
            assert running["qualityConfidence"]["coverage"]["conclusivePercent"] == 50
            live_running = live_snapshot()
            assert live_running["runId"] == "plan-view-contract" and live_running["progress"]["percent"] == 50

            call("run", "update", "--run-dir", str(run_dir), "--test-id", "CHECKOUT-002", "--status", "running")
            call("run", "update", "--run-dir", str(run_dir), "--test-id", "CHECKOUT-002", "--status", "passed", "--actual", "Observed rejection")
            call("run", "complete", "--run-dir", str(run_dir), "--cut-line", "Persona journeys were not exercised by this execution-plan viewer contract.")
            complete = snap(root, plan_path, run_dir)
            assert complete["status"] == "completed" and complete["progress"]["percent"] == 100
            assert complete["timing"]["estimatedRemainingSeconds"] == 0
            assert complete["qualityConfidence"]["confidenceInQuality"]["band"] == "guarded"
            assert complete["qualityConfidence"]["coverage"]["conclusivePercent"] == 100
            assert complete["qualityConfidence"]["coverage"]["evidenceBacked"] == 0
            assert live_snapshot()["progress"]["percent"] == 100
            report = (run_dir / "report.html").read_text(encoding="utf-8")
            assert "Normative oracle" in report and "Suspected defect was not reproduced" in report

            outside = root / "outside.json"
            outside.write_text(json.dumps(plan), encoding="utf-8")
            rejected = call("plan-view", "snapshot", "--root", str(root), "--plan", str(outside), ok=False)
            assert "inside" in rejected.stderr
        finally:
            viewer.terminate()
            try:
                viewer.wait(timeout=4)
            except subprocess.TimeoutExpired:
                viewer.kill()
            assert not ready_path.exists(), "viewer did not remove its ready file on shutdown"

    print(json.dumps({"status": "PASS", "contract": "carbon.execution-plan-view/v1", "liveRunDiscovery": True, "persistentViewer": True, "privateContextExcluded": True}))
    return 0


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