#!/usr/bin/env python3
"""Fail-closed preflight for exact repair candidates.

Verifies original source before-hashes and candidate prompt hashes against
Jim's named exports. Does not apply. Does not write the original worktree.
Does not import gold builders.

Usage:
  python3 preflight.py
  python3 preflight.py --self-check
  python3 preflight.py --check-source-manifest
"""
from __future__ import annotations

import argparse
import hashlib
import json
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
STAGING = HERE.parent
SOURCE = Path("/Users/jimmotes/kredo-gold-corpus-dara-wave2")
INDEX = STAGING / "EXACT_REPAIR_CANDIDATES.json"
MANIFEST = (
    SOURCE
    / "gold_responses/v1/reviews/WAVES_2_18_POST_CONTAMINATION_EXTERNAL_CHECKPOINT_SHA256SUMS.txt"
)
EXPECTED_MANIFEST_SHA256 = (
    "a6499a91dff196ac9806e35160b8164d869ddb364654c83bcbe3445eb2f45c49"
)

sys.path.insert(0, str(HERE))
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 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}: got {prompt_sha} expected {item['current_prompt_sha256']}"
        )
    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"]:
        fail(f"extracted prompt hash mismatch {item['prompt_id']}")
    if prompt_sha != item["candidate_prompt_sha256"]:
        fail(
            f"candidate prompt hash drift {item['prompt_id']}: got {prompt_sha} expected {item['candidate_prompt_sha256']}"
        )
    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']}")
    if item.get("implementation_ready") is not False:
        fail(f"implementation_ready must be false {item['prompt_id']}")
    src = json.loads((SOURCE / item["current_path"]).read_text(encoding="utf-8"))
    for key in (
        "positive_responses",
        "negative_controls",
        "near_miss_controls",
        "lens_annotations",
        "dimensions",
        "review_status",
    ):
        if src.get(key) != obj.get(key):
            fail(f"candidate mutated preserved field {key} on {item['prompt_id']}")


def verify_all(index: dict) -> None:
    if index.get("applied") is not False:
        fail("package applied must be false")
    items = index.get("items") or []
    if len(items) != 6:
        fail(f"expected 6 items, got {len(items)}")
    extracted = extract_all()
    for item in items:
        pid = item["prompt_id"]
        if pid not in extracted:
            fail(f"no extractor for {pid}")
        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}")
        if item["jim_note_pointer"] != extracted[pid]["note_pointer"]:
            fail(f"note pointer mismatch {pid}")
    print("PASS source-before-hashes and candidate prompt hashes (6/6)")


def self_check(index: dict) -> None:
    verify_all(index)
    item = index["items"][0]
    stale = "0" * 64
    try:
        verify_source_item(item, expected_file_sha=stale)
    except PreflightFailure:
        print("PASS stale-source-hash negative test (fail closed)")
    else:
        fail("stale-source-hash negative test did not fail")
    extracted = extract_all()
    broken = dict(item)
    broken["candidate_prompt_sha256"] = stale
    try:
        verify_candidate_item(broken, extracted[item["prompt_id"]])
    except PreflightFailure:
        print("PASS stale-candidate-prompt-hash negative test (fail closed)")
    else:
        fail("stale-candidate-prompt-hash negative test did not fail")


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
            print(f"MISSING {rel}", file=sys.stderr)
            continue
        if sha256_file(path) == digest:
            ok += 1
        else:
            mismatch += 1
            print(f"MISMATCH {rel}", file=sys.stderr)
    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)
