#!/usr/bin/env python3
"""Synthetic coverage-ledger records; execute the pinned, unchanged Node CLI."""
from copy import deepcopy
import hashlib
import json
from pathlib import Path
import subprocess
import sys
import tempfile

validator = Path(sys.argv[1]).resolve()
assert hashlib.sha256(validator.read_bytes()).hexdigest() == "2eb280bd2e33c002916f86db9b29f9edfedb6454e5db973c766290465b868ac8"
refs = {"surface": "synthetic/handler.ts#update", "boundary": "synthetic/policy.ts#check",
        "subsystem": "synthetic-service", "attack_class": "ATTACK-CLASSES.md#Access control"}
result = subprocess.run(["node", "-e", "const v=require(process.argv[1]);let s='';process.stdin.on('data',c=>s+=c);process.stdin.on('end',()=>process.stdout.write(v.canonicalCoverageId(JSON.parse(s))));", str(validator)],
                        input=json.dumps(refs), capture_output=True, text=True, check=True, timeout=10)
coverage_id = result.stdout

def check(agent):
    return {"agent_id": agent, "reviewed_paths": ["synthetic/handler.ts"],
            "invariant": "Synthetic fixture invariant.", "method": "local",
            "result": "Synthetic record only; no target operation executed.",
            "artifact": f"agents/{agent}/artifacts/probe.txt"}

old = {"wave": 1, "status": "blocked", "agent_id": "worker-1",
       "reviewed_paths": ["synthetic/handler.ts"], "local_checks": [check("worker-1")],
       "result_fingerprints": [], "unresolved": ["Synthetic capability unavailable."],
       "reassignment_reason": "Synthetic reassignment for an independent check."}
base = {"coverage_id": coverage_id, "canonical_refs": refs, "surface": "Synthetic update",
        "boundary": "Synthetic policy", "subsystem": "Synthetic service", "attack_class": "Access control",
        "starting_paths": ["synthetic/handler.ts"], "ordinary_attack_class_block": "ATTACK-CLASSES.md#Access control",
        "selected_companion_blocks": [], "excluded_blocks": [], "prior_status": "new",
        "attempts": [old], "wave": 2, "status": "in_progress", "agent_id": "worker-2",
        "reviewed_paths": [], "local_checks": [], "result_fingerprints": [], "unresolved": []}
closed = deepcopy(base)
closed.update(status="covered", reviewed_paths=["synthetic/handler.ts"], local_checks=[check("worker-2")])
reused_owner = deepcopy(base)
reused_owner["agent_id"] = "worker-1"
mixed = deepcopy(closed)
mixed["local_checks"] = [check("worker-1")]
relabelled = deepcopy(closed)
relabelled["local_checks"][0]["artifact"] = old["local_checks"][0]["artifact"]
deferred = deepcopy(base)
deferred["attempts"][0].update(status="candidate", result_fingerprints=["synthetic-candidate"],
                              unresolved=["Synthetic validation remains incomplete."])
deferred.update(status="deferred", agent_id=None, unresolved=["Synthetic scheduling pause."])
unresolved = deepcopy(closed)
unresolved["unresolved"] = ["Synthetic unresolved fact."]
fresh_check_owner = deepcopy(closed)
fresh_check_owner["local_checks"] = [check("worker-3")]

cases = [
    ("fresh-in-progress", base, 0, "PASS: 1 coverage units valid"),
    ("fresh-covered-no-files", closed, 0, "PASS: 1 coverage units valid"),
    ("reused-assignment-owner", reused_owner, 1, "current assignment owner must be fresh"),
    ("archived-check-reused", mixed, 1, "prior assignment owner evidence must remain"),
    ("relabelled-old-artifact", relabelled, 1, "artifact from an archived attempt cannot be reused"),
    ("candidate-archived-and-deferred", deferred, 0, "PASS: 1 coverage units valid"),
    ("covered-with-unresolved-fact", unresolved, 1, "must keep this array empty"),
    ("fresh-additional-check-owner", fresh_check_owner, 0, "PASS: 1 coverage units valid"),
]
print("Python " + sys.version.split()[0])
print(subprocess.run(["node", "--version"],capture_output=True,text=True,check=True).stdout.strip())
with tempfile.TemporaryDirectory(prefix="audit-ledger-replay-") as temp:
    directory = Path(temp)
    for name, row, expected, diagnostic in cases:
        assert row["coverage_id"] == coverage_id
        assert not (directory / "agents").exists()
        file = directory / (name + ".json")
        file.write_text(json.dumps([row], indent=2), encoding="utf-8")
        result = subprocess.run(["node", str(validator), str(file)], cwd=directory,
                                capture_output=True, text=True, timeout=10)
        output = result.stdout + result.stderr
        assert result.returncode == expected, (name, result.returncode, output)
        assert diagnostic in output, (name, output)
        if name == "relabelled-old-artifact":
            assert "local check requires an artifact owned by agent" in output
        print(json.dumps({"case": name, "exit": result.returncode, "matched": diagnostic}, separators=(",", ":")))
        if name == "archived-check-reused":
            print("--- CLI diagnostic for archived-check-reused ---")
            print(output.strip())
    print("PASS: 8 CLI cases; coverage ID preserved; referenced artifact files were never created")
