#!/usr/bin/env python3
"""End-to-end contract for CARBON's adaptive intelligence layer."""

from __future__ import annotations

import json
import subprocess
import sys
import tempfile
from pathlib import Path


PLUGIN = Path(__file__).resolve().parents[1]
INTELLIGENCE = PLUGIN / "runtime" / "carbon" / "scripts" / "carbon_intelligence.py"
FRAMEWORK = PLUGIN / "runtime" / "carbon" / "scripts" / "carbon_framework.py"
RUNNER = PLUGIN / "runtime" / "carbon" / "scripts" / "carbon_run.py"


def run(*args: str) -> str:
    result = subprocess.run(args, text=True, capture_output=True, check=False)
    if result.returncode:
        raise AssertionError(f"Command failed ({result.returncode}): {' '.join(args)}\n{result.stdout}\n{result.stderr}")
    return result.stdout


def call(action: str, root: Path, *extra: str) -> dict:
    return json.loads(run(sys.executable, str(INTELLIGENCE), action, "--root", str(root), *extra))


def write(path: Path, value: str) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(value, encoding="utf-8")


with tempfile.TemporaryDirectory(prefix="carbon-intelligence-") as temporary:
    root = Path(temporary)
    write(root / "src" / "accounts.py", "def get_account(account_id):\n    return {'id': account_id}\n")
    write(root / "tests" / "accounts_test.py", "def test_account():\n    assert True\n")
    write(root / "scripts" / "quality-contract-test.py", "assert True\n")
    spec = {
        "openapi": "3.0.3",
        "info": {"title": "Account API", "version": "1"},
        "paths": {
            "/api/accounts/{id}": {
                "get": {
                    "operationId": "getAccount",
                    "security": [{"bearer": []}],
                    "responses": {"200": {"description": "ok"}, "403": {"description": "denied"}},
                }
            }
        },
    }
    write(root / "openapi.json", json.dumps(spec))
    source_before = {
        path.relative_to(root).as_posix(): path.read_bytes()
        for path in root.rglob("*") if path.is_file() and ".carbon" not in path.parts
    }

    initial = call("memory", root)
    assert initial["freshness"] == "initialized"
    assert initial["current"]["counts"]["tests"] == 2
    current = call("memory", root)
    assert current["freshness"] == "current"
    write(root / "src" / "accounts.py", "def get_account(account_id):\n    return {'id': account_id, 'owner': 'tenant'}\n")
    stale = call("memory", root)
    assert stale["freshness"] == "stale" and "source" in stale["changedDomains"]
    assert any("product model" in item["invalidates"] for item in stale["invalidations"])

    prepared = json.loads(run(
        sys.executable, str(FRAMEWORK), "prepare", "--root", str(root),
        "--request", "test account authorization", "--target", "https://local.test",
        "--size", "quick", "--openapi", str(root / "openapi.json"),
    ))
    plan_path = root / ".carbon" / "framework" / "orchestration-plan.json"
    plan = json.loads(plan_path.read_text(encoding="utf-8"))
    assert plan["projectMemory"]["schema"] == "carbon.project-memory/v1"
    assert prepared["projectMemoryFreshness"] in {"current", "stale"}
    auth = next(row for row in plan["tests"] if row.get("type") == "api-authorization")
    auth_id = auth["id"]

    for run_id in ("security-a", "security-b"):
        run_dir = root / ".carbon" / "runs" / run_id
        run(sys.executable, str(RUNNER), "init", "--root", str(root), "--plan", str(plan_path), "--mode", "quick", "--target", "https://local.test", "--run-id", run_id)
        run(sys.executable, str(RUNNER), "start", "--run-dir", str(run_dir))
        run(sys.executable, str(RUNNER), "update", "--run-dir", str(run_dir), "--test-id", auth_id, "--status", "running")
        run(
            sys.executable, str(RUNNER), "update", "--run-dir", str(run_dir), "--test-id", auth_id,
            "--status", "failed", "--actual", "Cross-tenant authorization leaked an account owner",
            "--evidence", f"evidence/{run_id}-authorization.json",
        )
        run(
            sys.executable, str(RUNNER), "finding", "--run-dir", str(run_dir), "--severity", "high",
            "--category", "security", "--dimension", "security",
            "--title", "Cross-tenant account authorization leak", "--detail", "Wrong-tenant request returned the account owner",
            "--test-id", auth_id, "--starting-state", "two tenant fixtures", "--steps", "request account with wrong tenant token",
            "--expected", "403 policy-safe denial", "--actual", "200 exposed owner", "--evidence", f"evidence/{run_id}-authorization.json",
            "--code-location", "src/accounts.py", "--regression-test", auth_id,
        )
        if run_id == "security-a":
            run(
                sys.executable, str(RUNNER), "finding", "--run-dir", str(run_dir), "--severity", "low",
                "--category", "console", "--dimension", "operational",
                "--title", "Fresh page load requests a missing favicon",
                "--detail", "The browser failed to load /favicon.ico with HTTP 404.",
                "--test-id", auth_id, "--evidence", "evidence/favicon-console.log",
            )

    graph = call("graph", root)
    kinds = graph["summary"]["byKind"]
    assert kinds["project"] == 1 and kinds["test"] >= 1 and kinds["run"] == 2
    assert any(edge["relation"] == "covered-by" for edge in graph["edges"])
    why = call("why-test", root, "--test-id", auth_id)
    assert why["test"]["id"] == auth_id and why["why"] and why["observedResults"]
    assert why["decisionRule"].startswith("Run this test")

    failures = call("failures", root)
    cluster = next(item for item in failures["clusters"] if item["classification"] == "security")
    assert cluster["occurrences"] == 2
    assert cluster["reproducibility"] == "repeatable"
    assert len(cluster["reproPaths"]) == 2
    favicon_cluster = next(item for item in failures["clusters"] if "favicon" in item["title"].lower())
    assert favicon_cluster["classification"] == "product-defect"
    assert "hypoth" in failures["boundary"].lower()

    benchmark = call("benchmark", root)
    assert benchmark["expected"] == 15 and benchmark["detected"] == 15
    assert benchmark["precision"] == benchmark["recall"] == benchmark["f1"] == 1.0
    assert not benchmark["missedSeeds"] and not benchmark["unexpectedSignals"]

    complete = call("all", root)
    report_path = Path(complete["reportPath"])
    report = report_path.read_text(encoding="utf-8")
    assert 'class="decision-hero' in report and 'class="evidence-spine"' in report
    assert "Coverage at a glance" not in report and "Confidence dimensions" in report
    assert "Risk × evidence" in report
    for phrase in (
        "Readiness doctor", "Multidimensional confidence", "Evidence graph",
        "Failure clusters", "Freshness and invalidation", "Seeded-defect dogfood benchmark",
        'id="search"', "data-tab", "Expand details",
    ):
        assert phrase in report, phrase
    assert complete["readiness"]["oneCommandBehavior"]
    assert len(complete["readiness"]["confidence"]["dimensions"]) == 8

    latest_report = (root / ".carbon" / "runs" / "security-b" / "report.html").read_text(encoding="utf-8")
    for phrase in ('id="report-search"', 'id="status-filter"', 'id="priority-filter"', "Multidimensional confidence", "applyReportFilters", "Expand details"):
        assert phrase in latest_report, phrase

    source_after = {
        path.relative_to(root).as_posix(): path.read_bytes()
        for path in root.rglob("*") if path.is_file() and ".carbon" not in path.parts
    }
    expected_source = dict(source_before)
    expected_source["src/accounts.py"] = (root / "src" / "accounts.py").read_bytes()
    assert source_after == expected_source, "intelligence actions changed product files outside .carbon"

print("PASS: adaptive doctor, evidence lineage, why-test, failure clustering/repro, project-memory invalidation, interactive reports, multidimensional confidence, and 15/15 seeded dogfood benchmark verified.")
