#!/usr/bin/env python3
"""E128 Standalone Offline Verifier.

Standard library ONLY. Imports ZERO CAIN runtime code.
Safe to execute as an unprivileged user (e.g., nobody) on a read-only bundle copy.
Verifies:
  1. Every file SHA-256 listed in MANIFEST.json
  2. RFC 6962 binary Merkle root over all raw experiment records in E128_EXPERIMENTS.jsonl
  3. All 32 required evidence fields present on every experiment record
  4. Hash-chained event log integrity in E128_EVENTS.jsonl
  5. Baseline manifest integrity & immutable baseline commits
  6. Preregistration presence & sample-size fidelity (no silent truncation)
  7. Eight specialized workers linked to 100 registered identities, all 8 with real LLM trials
  8. Separation of scientific_verdict and integrity_verdict
  9. Honest AGI status ('AGI NOT ESTABLISHED') & visible FAIL/BLOCKED/NOT_TESTED records
 10. All 26 release gates with valid status values
 11. Three-site homepage snapshots & tamper-detection self-test
"""
from __future__ import annotations

import hashlib
import json
import re
import sys
from pathlib import Path

REQUIRED_EXPERIMENT_FIELDS = {
    "experiment_id", "campaign_id", "evolution", "worker_id", "worker_type",
    "worker_model", "model_version", "hypothesis", "task_family", "environment_id",
    "dataset_fingerprint", "configuration_hash", "code_commit", "seed", "control_group",
    "baseline", "sample_size", "outcome", "effect_size", "confidence_interval",
    "statistical_test", "p_value", "correction_method", "compute_used", "token_usage",
    "cost", "duration", "limitations", "reproduction_status", "scientific_verdict",
    "integrity_verdict", "timestamp",
}
VALID_SCI_VERDICTS = {"PASS", "PARTIAL", "FAIL", "INTERIM", "BLOCKED", "NOT_TESTED"}
VALID_INT_VERDICTS = {"VERIFIED", "PARTIAL", "INVALID", "NOT_TESTED"}
VALID_GATE_STATUSES = {"PASS", "PARTIAL", "FAIL", "BLOCKED", "NOT_TESTED"}

FAILURES: list[str] = []
CHECKS = 0


def check(cond: bool, name: str, detail: str = "") -> None:
    global CHECKS
    CHECKS += 1
    status = "PASS" if cond else "FAIL"
    print(f"{status} {name}" + (f" {detail}" if detail else ""))
    if not cond:
        FAILURES.append(name)


def sha256_file(p: Path) -> str:
    h = hashlib.sha256()
    with p.open("rb") as fh:
        for chunk in iter(lambda: fh.read(65536), b""):
            h.update(chunk)
    return h.hexdigest()


def canon_str(obj) -> str:
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=True)


def merkle_root(leaf_hashes: list[str]) -> str:
    if not leaf_hashes:
        return hashlib.sha256(b"").hexdigest()
    level = [hashlib.sha256(b"\x00" + bytes.fromhex(h)).digest() for h in leaf_hashes]
    while len(level) > 1:
        nxt = []
        for i in range(0, len(level), 2):
            if i + 1 < len(level):
                nxt.append(hashlib.sha256(b"\x01" + level[i] + level[i + 1]).digest())
            else:
                nxt.append(level[i])
        level = nxt
    return level[0].hex()


def load_json(p: Path):
    return json.loads(p.read_text(encoding="utf-8"))


def load_jsonl(p: Path) -> list[dict]:
    return [json.loads(ln) for ln in p.read_text(encoding="utf-8").splitlines() if ln.strip()]


def main() -> int:
    root = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).resolve().parent
    print(f"E128 standalone offline verifier root={root}")

    man = load_json(root / "MANIFEST.json")
    check(man.get("evolution") == "E128", "manifest_evolution", str(man.get("evolution")))
    check(man.get("entity") == "FIRME AI CORPORATION", "manifest_entity", str(man.get("entity")))
    check(man.get("agi_status") == "AGI NOT ESTABLISHED", "manifest_agi_status", str(man.get("agi_status")))

    for entry in man["files"]:
        fp = root / entry["path"]
        ok = fp.exists() and sha256_file(fp) == entry["sha256"]
        check(ok, f"file_sha256:{entry['path']}", "" if ok else "MISMATCH_OR_MISSING")

    # Baseline manifest
    base = load_json(root / "E128_BASELINE_MANIFEST.json")
    base_body = base["manifest"]
    check(
        hashlib.sha256(canon_str(base_body).encode("utf-8")).hexdigest() == base["manifest_sha256"],
        "baseline_manifest_digest",
    )
    check(base_body.get("baseline_all_passed") is True, "baseline_all_passed")
    check(
        base_body["repository_commits"]["required_baseline_e127"]["ok"]
        and base_body["repository_commits"]["implementation_e127"]["ok"]
        and base_body["repository_commits"]["previous_intelligence_e126b"]["ok"],
        "baseline_commits_verified",
    )

    # Preregistration
    prereg = load_json(root / "E128_PREREGISTRATION.json")
    check(prereg.get("status") == "FROZEN_BEFORE_CONFIRMATORY_RUNS", "preregistration_frozen")
    check(len(prereg.get("domains", {})) == 8, "preregistration_8_domains")

    # Workers
    workers = load_json(root / "E128_WORKERS_REGISTRY.json")
    check(workers.get("registered_identities_total") == 100, "registered_identities_100")
    check(len(workers.get("workers", [])) == 8, "specialized_workers_8")
    check(
        all(w["execution_stats"]["llm_trials_completed"] > 0 for w in workers["workers"]),
        "all_8_workers_executed_real_llm_trials",
    )
    check(
        all(w["execution_stats"]["total_cost_usd"] == 0.0 for w in workers["workers"]),
        "zero_unauthorized_paid_spend",
    )

    # Experiments & Merkle root
    exps = load_jsonl(root / "E128_EXPERIMENTS.jsonl")
    check(len(exps) == 2000, "experiments_count_2000", str(len(exps)))
    exp_ids = {e["experiment_id"] for e in exps}
    check(len(exp_ids) == len(exps), "experiments_unique_ids", str(len(exp_ids)))

    fields_ok = True
    hashes_ok = True
    verdicts_ok = True
    leaf_hashes = []
    for e in exps:
        if not REQUIRED_EXPERIMENT_FIELDS.issubset(e.keys()):
            fields_ok = False
        body = {k: v for k, v in e.items() if k != "record_sha256"}
        calc = hashlib.sha256(canon_str(body).encode("utf-8")).hexdigest()
        if calc != e.get("record_sha256"):
            hashes_ok = False
        if e.get("scientific_verdict") not in VALID_SCI_VERDICTS or e.get("integrity_verdict") not in VALID_INT_VERDICTS:
            verdicts_ok = False
        leaf_hashes.append(e["record_sha256"])

    check(fields_ok, "all_32_evidence_fields_present")
    check(hashes_ok, "all_2000_record_sha256_valid")
    check(verdicts_ok, "separate_valid_scientific_and_integrity_verdicts")

    computed_merkle = merkle_root(leaf_hashes)
    snap = load_json(root / "E128_CAMPAIGN_SNAPSHOT.json")
    check(computed_merkle == snap.get("merkle_root") == man.get("merkle_root"), "merkle_root_match", computed_merkle[:16])

    # Tamper detection self-test (in-memory)
    tampered = list(leaf_hashes)
    tampered[0] = "f" * 64 if tampered[0] != "f" * 64 else "0" * 64
    check(merkle_root(tampered) != computed_merkle, "tamper_detection_merkle_flip")

    # LLM classification honesty
    llm_exps = [e for e in exps if e["worker_type"] == "model_driven_llm"]
    llm_workers = {e["worker_id"] for e in llm_exps}
    check(len(llm_workers) == 8 and len(llm_exps) == 64, "llm_trials_8_workers_64_trials", f"w={len(llm_workers)} n={len(llm_exps)}")
    check(all(e["token_usage"]["total_tokens"] > 0 for e in llm_exps), "llm_trials_nonzero_tokens")

    # Event hash chain
    events = load_jsonl(root / "E128_EVENTS.jsonl")
    prev = "0" * 64
    ev_ok = True
    for idx, ev in enumerate(events, start=1):
        integ = ev.get("integrity") or {}
        body = {k: v for k, v in ev.items() if k != "integrity"}
        exp_h = hashlib.sha256((prev + canon_str(body)).encode("utf-8")).hexdigest()
        if ev.get("seq") != idx or integ.get("prev") != prev or integ.get("hash") != exp_h:
            ev_ok = False
            break
        prev = integ["hash"]
    check(ev_ok and len(events) > 0, "event_chain_valid", f"count={len(events)}")

    # Governance & kill switch
    gov = load_json(root / "E128_GOVERNANCE_SUMMARY.json")
    check(gov.get("all_tests_pass") is True, "governance_security_suite_pass")
    check(gov.get("unauthorized_effects") == 0 and gov.get("post_kill_effects") == 0, "zero_unauthorized_and_post_kill_effects")
    check(gov.get("receipt_chain_valid") is True, "governance_receipt_chain_valid")

    # Public evidence registry
    reg = load_json(root / "E128_EVIDENCE_REGISTRY.json")
    check(reg.get("agi_status") == "AGI NOT ESTABLISHED", "registry_agi_not_established")
    check(len(reg.get("records", [])) >= 46, "registry_preserves_e127_plus_e128", str(len(reg.get("records", []))))
    check(any(r["scientific_status"] == "FAIL" for r in reg["records"]), "registry_preserves_fail_records")
    check(any(r["scientific_status"] == "BLOCKED" for r in reg["records"]), "registry_preserves_blocked_records")

    # Release gates (26 gates)
    score = load_json(root / "E128_SCORECARD.json")
    gates = score.get("gates", [])
    check(len(gates) == 26, "release_gates_26", str(len(gates)))
    check(all(g.get("status") in VALID_GATE_STATUSES for g in gates), "release_gates_valid_statuses")

    # Three-site homepage snapshots
    for fname in ("clawx.html", "studio.html", "mcpgate.html"):
        hp = root / "homepages" / fname
        txt = hp.read_text(encoding="utf-8", errors="replace") if hp.exists() else ""
        check(hp.exists() and "E128-" in txt and "AGI NOT ESTABLISHED" in txt, f"homepage_snapshot:{fname}")
        bad = re.search(r"(?<!not )100\s+(active|running)\s+agents", txt, flags=re.I)
        check(bad is None, f"no_fabricated_100_active:{fname}")

    passed = CHECKS - len(FAILURES)
    print(f"\n{passed}/{CHECKS} checks passed; {len(FAILURES)} failed")
    if FAILURES:
        print("FAILURES:", FAILURES)
        return 1
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
