#!/usr/bin/env python3
"""Contract test for durable, decision-changing CARBON human context."""

from __future__ import annotations

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


PLUGIN = Path(__file__).resolve().parents[1]
SCRIPT = PLUGIN / "runtime" / "carbon" / "scripts" / "carbon_human.py"
WORKSPACE = PLUGIN / "ui" / "human.html"
sys.path.insert(0, str(PLUGIN / "runtime" / "carbon" / "scripts"))
from carbon_quality_confidence import assess_quality_confidence  # noqa: E402


def run(*args: str) -> dict:
    result = subprocess.run(["python3", str(SCRIPT), *args], check=True, capture_output=True, text=True)
    return json.loads(result.stdout)


with tempfile.TemporaryDirectory(prefix="carbon-human-contract-") as temporary:
    root = Path(temporary)
    (root / "package.json").write_text(json.dumps({"name": "checkout-demo"}), encoding="utf-8")
    (root / "src").mkdir()
    (root / "src" / "checkout.ts").write_text(
        "const token = session.token; async function checkout() { return payment(); } // production deploy", encoding="utf-8"
    )
    (root / ".carbon" / "runs" / "run-1").mkdir(parents=True)
    (root / ".carbon" / "runs" / "run-1" / "run.json").write_text(json.dumps({
        "runId": "run-1", "updatedAt": "2026-08-28T00:00:00Z", "targetRoot": str(root),
        "tests": [{"id": "PAY-001", "status": "failed", "priority": "P0", "title": "Checkout payment", "actual": "Payment failed", "evidence": ["evidence/payment.json"]}],
        "findings": [{"id": "F-001", "severity": "high", "title": "Payment retry may duplicate charge"}],
    }), encoding="utf-8")

    generated = run("generate", "--root", str(root), "--size", "quick", "--scope", "production checkout release")
    assert generated["summary"]["status"] == "pending"
    assert generated["summary"]["open"] <= 5
    questions = generated["context"]["questions"]
    assert any(row["key"] == "release-context" for row in questions)
    assert any(row["key"] == "failure-consequence" for row in questions)
    assert all("question" in row and "why" in row and "decisionImpact" in row for row in questions)
    assert all(isinstance(row.get("options"), list) and row["options"] for row in questions)
    assert (root / ".carbon" / "human" / "decision-context.json").stat().st_mode & 0o777 == 0o600

    release = next(row for row in questions if row["key"] == "release-context")
    answered = run("answer", "--root", str(root), "--question", release["id"], "--answer", "This is a production launch next Tuesday; finance owns go/no-go.", "--answered-by", "product owner")
    assert answered["question"]["status"] == "answered"
    repeated = run("generate", "--root", str(root), "--size", "quick", "--scope", "production checkout release")
    retained = next(row for row in repeated["context"]["questions"] if row["id"] == release["id"])
    assert retained["answer"].startswith("This is a production launch")
    assert repeated["summary"]["open"] >= 1

    failure = next(row for row in repeated["context"]["questions"] if row["key"] == "failure-consequence")
    selected = run("answer", "--root", str(root), "--question", failure["id"], "--option-id", "hold", "--comment", "Duplicate charges are unacceptable for any production customer.")
    assert selected["question"]["selectedOptionId"] == "hold"
    noted = run("comment", "--root", str(root), "--question", "project", "--comment", "Finance is the accountable release owner.", "--author", "product owner")
    assert noted["comment"]["questionId"] == "project"
    report = run("report", "--root", str(root))
    report_path = Path(report["report"]["reportPath"])
    assert report_path.is_file()
    report_html = report_path.read_text(encoding="utf-8")
    assert "Human decision context" in report_html and "rel=\"icon\"" in report_html and "AI" in report_html

    confidence = assess_quality_confidence({
        "targetRoot": str(root),
        "tests": [{"id": "PASS-001", "status": "passed", "priority": "P2", "actual": "Observed", "evidence": ["evidence/pass.json"]}],
    })
    assert confidence["humanDecisionContext"]["status"] == "pending"
    assert "Human decision context" in confidence["confidenceInQuality"]["basis"]
    assert confidence["confidenceInQuality"]["band"] in {"moderate", "guarded"}
    assert any("carbon-human" in item for item in confidence["whatWouldChangeConfidence"])

workspace = WORKSPACE.read_text(encoding="utf-8")
assert '"/api/human-context"' in workspace
assert "data-option" in workspace and "Save answer" in workspace
assert "Add context anywhere" in workspace and "project-level observation" in workspace
assert "alert(" not in workspace and "confirm(" not in workspace

print("PASS: project-specific human questions, quick-answer options, durable comments and reports, non-blocking confidence qualification, and secure local persistence verified.")
