#!/usr/bin/env python3
"""R2 fail-closed preflight. Does not apply. Does not write the original worktree."""
from __future__ import annotations

import argparse
import copy
import json
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
R2 = HERE.parent
R1 = R2.parent
R1_TOOLS = R1 / "tools"
SOURCE = Path("/Users/jimmotes/kredo-gold-corpus-dara-wave2")
INDEX = R2 / "EXACT_REPAIR_CANDIDATES.json"
MANIFEST = (
    SOURCE
    / "gold_responses/v1/reviews/WAVES_2_18_POST_CONTAMINATION_EXTERNAL_CHECKPOINT_SHA256SUMS.txt"
)
EXPECTED_MANIFEST_SHA256 = (
    "a6499a91dff196ac9806e35160b8164d869ddb364654c83bcbe3445eb2f45c49"
)
EXPECTED_ITEMS = {
    "SS-025": {
        "wave": "wave_04",
        "current_path": "gold_responses/v1/drafts/wave_04/SS-025.json",
    },
    "SS-008": {
        "wave": "wave_05",
        "current_path": "gold_responses/v1/drafts/wave_05/SS-008.json",
    },
    "SS-016": {
        "wave": "wave_05",
        "current_path": "gold_responses/v1/drafts/wave_05/SS-016.json",
    },
    "ADR-015": {
        "wave": "wave_09",
        "current_path": "gold_responses/v1/drafts/wave_09/ADR-015.json",
    },
    "SS-023": {
        "wave": "wave_10",
        "current_path": "gold_responses/v1/drafts/wave_10/SS-023.json",
    },
    "SS-035": {
        "wave": "wave_10",
        "current_path": "gold_responses/v1/drafts/wave_10/SS-035.json",
    },
}

sys.path.insert(0, str(R1_TOOLS))
from extract_jim_prompt import extract_all, sha256_file, sha256_text  # noqa: E402


def artifact_sha256(art: dict) -> str:
    tmp = {k: v for k, v in art.items() if k != "artifact_sha256"}
    canonical = json.dumps(tmp, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
    return sha256_text(canonical)


class PreflightFailure(Exception):
    pass


def fail(msg: str) -> None:
    raise PreflightFailure(msg)


def load_index() -> dict:
    if not INDEX.is_file():
        fail(f"missing index {INDEX}")
    return json.loads(INDEX.read_text(encoding="utf-8"))


def allowed_fields(item: dict) -> set[str]:
    allowed = set(item.get("mechanical_fields") or [])
    allowed.update(item.get("allowlisted_metadata_fields") or [])
    allowed.add("artifact_sha256")
    allowed.add("prompt_sha256")
    allowed.add("prompt_text")
    return allowed


def verify_identity(items: list[dict]) -> None:
    if len(items) != 6:
        fail(f"expected 6 items, got {len(items)}")
    ids = [it.get("prompt_id") for it in items]
    if len(ids) != len(set(ids)):
        fail(f"duplicate prompt_id in index: {ids}")
    got = set(ids)
    want = set(EXPECTED_ITEMS)
    if got != want:
        fail(f"prompt_id set mismatch got={sorted(got)} want={sorted(want)}")
    for it in items:
        pid = it["prompt_id"]
        exp = EXPECTED_ITEMS[pid]
        if it.get("wave") != exp["wave"]:
            fail(f"{pid} wave {it.get('wave')} != {exp['wave']}")
        if it.get("current_path") != exp["current_path"]:
            fail(f"{pid} current_path {it.get('current_path')} != {exp['current_path']}")


def verify_root_delta(src: dict, cand: dict, item: dict) -> None:
    allowed = allowed_fields(item)
    keys = set(src) | set(cand)
    for key in sorted(keys):
        if key in allowed:
            continue
        if key not in src:
            fail(f"{item['prompt_id']} added unrelated field {key}")
        if key not in cand:
            fail(f"{item['prompt_id']} removed field {key}")
        if src[key] != cand[key]:
            fail(f"{item['prompt_id']} unrelated field change {key}")


def verify_source_item(item: dict, *, expected_file_sha: str | None = None) -> None:
    rel = item["current_path"]
    path = SOURCE / rel
    if not path.is_file():
        fail(f"source missing {path}")
    file_sha = sha256_file(path)
    want_file = expected_file_sha if expected_file_sha is not None else item["current_file_sha256"]
    if file_sha != want_file:
        fail(f"source file hash drift {rel}: got {file_sha} expected {want_file} (fail closed)")
    obj = json.loads(path.read_text(encoding="utf-8"))
    if obj.get("prompt_id") != item["prompt_id"]:
        fail(f"source prompt_id mismatch {rel}")
    prompt_sha = sha256_text(obj["prompt_text"])
    if prompt_sha != item["current_prompt_sha256"]:
        fail(f"source prompt hash drift {rel}")
    if obj.get("prompt_sha256") != prompt_sha:
        fail(f"source prompt_sha256 field inconsistent {rel}")
    if artifact_sha256(obj) != obj.get("artifact_sha256"):
        fail(f"source artifact_sha256 inconsistent {rel}")


def verify_candidate_item(item: dict, extracted: dict) -> None:
    path = Path(item["candidate_path"])
    if not path.is_file():
        fail(f"candidate missing {path}")
    file_sha = sha256_file(path)
    if file_sha != item["candidate_file_sha256"]:
        fail(f"candidate file hash drift {path.name}: got {file_sha} expected {item['candidate_file_sha256']}")
    obj = json.loads(path.read_text(encoding="utf-8"))
    if obj.get("prompt_id") != item["prompt_id"]:
        fail(f"candidate prompt_id mismatch {path.name}")
    if obj.get("prompt_text") != extracted["prompt_text"]:
        fail(f"candidate prompt_text != extracted Jim text {item['prompt_id']}")
    prompt_sha = sha256_text(obj["prompt_text"])
    if prompt_sha != extracted["prompt_sha256"] or prompt_sha != item["candidate_prompt_sha256"]:
        fail(f"candidate prompt hash drift {item['prompt_id']}")
    if obj.get("prompt_sha256") != prompt_sha:
        fail(f"candidate prompt_sha256 field inconsistent {item['prompt_id']}")
    if artifact_sha256(obj) != obj.get("artifact_sha256"):
        fail(f"candidate artifact_sha256 inconsistent {item['prompt_id']}")
    if artifact_sha256(obj) != item["candidate_artifact_sha256"]:
        fail(f"index candidate_artifact_sha256 drift {item['prompt_id']}")
    if item.get("applied") is not False:
        fail(f"applied must be false {item['prompt_id']}")
    src = json.loads((SOURCE / item["current_path"]).read_text(encoding="utf-8"))
    verify_root_delta(src, obj, item)
    r1_path = item.get("r1_candidate_path")
    if r1_path:
        r1 = json.loads(Path(r1_path).read_text(encoding="utf-8"))
        if item["prompt_id"] != "SS-035":
            if sha256_file(Path(r1_path)) != file_sha:
                fail(f"{item['prompt_id']} r2 candidate bytes must match R1")
        else:
            if r1.get("prompt_text") != obj.get("prompt_text"):
                fail("SS-035 r2 mutated prompt_text")
            if r1.get("positive_responses") != obj.get("positive_responses"):
                fail("SS-035 r2 mutated positive_responses")
            if r1.get("negative_controls") != obj.get("negative_controls"):
                fail("SS-035 r2 mutated negative_controls")
            if r1.get("near_miss_controls") != obj.get("near_miss_controls"):
                fail("SS-035 r2 mutated near_miss_controls")


def verify_all(index: dict) -> None:
    if index.get("applied") is not False:
        fail("package applied must be false")
    if index.get("auto_apply") is not False:
        fail("package auto_apply must be false")
    items = index.get("items") or []
    verify_identity(items)
    extracted = extract_all()
    for item in items:
        pid = item["prompt_id"]
        verify_source_item(item)
        verify_candidate_item(item, extracted[pid])
        if item["jim_export_sha256"] != extracted[pid]["export_sha256"]:
            fail(f"export hash mismatch {pid}")
    print("PASS source-before-hashes, unique IDs/wave/paths, and candidate prompt hashes (6/6)")


def expect_fail(fn, label: str) -> None:
    try:
        fn()
    except PreflightFailure:
        print(f"PASS {label} (fail closed)")
        return
    fail(f"{label} did not fail")


def self_check(index: dict) -> None:
    verify_all(index)
    items = index["items"]
    stale = "0" * 64
    expect_fail(lambda: verify_source_item(items[0], expected_file_sha=stale), "stale-source-hash negative test")
    extracted = extract_all()
    broken = dict(items[0])
    broken["candidate_prompt_sha256"] = stale
    expect_fail(
        lambda: verify_candidate_item(broken, extracted[broken["prompt_id"]]),
        "stale-candidate-prompt-hash negative test",
    )
    dup = copy.deepcopy(index)
    dup["items"] = [copy.deepcopy(items[0]) for _ in range(6)]
    expect_fail(lambda: verify_identity(dup["items"]), "duplicate-ID negative test")
    missing = copy.deepcopy(index)
    missing["items"] = [it for it in items if it["prompt_id"] != "ADR-015"]
    expect_fail(lambda: verify_identity(missing["items"]), "missing-ID negative test")

    src = json.loads((SOURCE / items[1]["current_path"]).read_text(encoding="utf-8"))
    cand = json.loads(Path(items[1]["candidate_path"]).read_text(encoding="utf-8"))
    mutated = copy.deepcopy(cand)
    mutated["review_status"] = "needs_revision"
    expect_fail(
        lambda: verify_root_delta(src, mutated, items[1]),
        "unrelated-field-change negative test",
    )


def check_source_manifest() -> None:
    if not MANIFEST.is_file():
        fail(f"missing source manifest {MANIFEST}")
    got = sha256_file(MANIFEST)
    if got != EXPECTED_MANIFEST_SHA256:
        fail(f"source manifest sha256 {got} != {EXPECTED_MANIFEST_SHA256}")
    ok = mismatch = missing = 0
    for line in MANIFEST.read_text(encoding="utf-8").splitlines():
        line = line.strip()
        if not line or line.startswith("#"):
            continue
        digest, rel = line.split(None, 1)
        if rel.startswith("*"):
            rel = rel[1:]
        path = SOURCE / rel
        if not path.is_file():
            missing += 1
            continue
        if sha256_file(path) == digest:
            ok += 1
        else:
            mismatch += 1
    print(f"SOURCE_MANIFEST ok={ok} mismatch={mismatch} missing={missing} total={ok+mismatch+missing}")
    if mismatch or missing:
        fail("source 994-member manifest drift (reported, not repaired)")
    print("PASS 994-member post-contamination manifest (read-only)")


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--self-check", action="store_true")
    parser.add_argument("--check-source-manifest", action="store_true")
    args = parser.parse_args()
    index = load_index()
    if args.self_check:
        self_check(index)
        return
    if args.check_source_manifest:
        check_source_manifest()
        return
    verify_all(index)


if __name__ == "__main__":
    try:
        main()
    except PreflightFailure as exc:
        print(f"FAIL {exc}", file=sys.stderr)
        raise SystemExit(2)
