#!/usr/bin/env python3
"""CAIN-42 Evolution 158 — Zero-CAIN-Import Standalone Offline Verifier.

Usage: python3 -I verify_e158_offline.py <bundle_dir>

Imports ONLY Python standard library + cryptography (for Ed25519). Imports ZERO
CAIN code. Independently verifies:
  1. File SHA-256 integrity for every listed manifest file.
  2. RFC-6962 style binary Merkle root recomputation & match with E158_MERKLE_ROOT.txt.
  3. Ed25519 signature over canonical manifest payload.
  4. Frozen preregistration SHA-256 commitment (no post-hoc edits).
  5. Sealed & replication salt SHA-256 commitments vs revealed salts.
  6. Unified organism 12-stage cycle hash-chain completeness & integrity.
  7. Parent-to-child SHA-256 source lineage & non-empty unified source diffs.
  8. Experiment completeness, negative results publication, and honest AGI/RSI status.
  9. Gate matrix consistency & honest non-inflation rules.
"""
from __future__ import annotations

import hashlib
import json
import sys
from pathlib import Path

REQUIRED_ARTIFACTS = [
    "FORENSIC_BASELINE.md",
    "E154_E157_RECONCILIATION.json",
    "evolution_lineage.json",
    "organism_architecture.json",
    "capability_inventory.json",
    "organism_health.json",
    "research_literature.json",
    "research_direction_log.json",
    "colony_registry.json",
    "agent_contributions.jsonl",
    "colony_experiments.jsonl",
    "hypothesis_preregistration.json",
    "experiment_registry.json",
    "experiment_results.jsonl",
    "research_proposer_comparison.json",
    "algorithm_candidates.json",
    "successor_lineage.json",
    "branching_lineage.json",
    "capability_retention.json",
    "scientific_memory_report.json",
    "cross_domain_transfer.json",
    "independent_replication.json",
    "external_benchmark_report.json",
    "anthropic_request_ledger.jsonl",
    "resource_usage.json",
    "security_report.json",
    "governance_report.json",
    "soak_report.json",
    "negative_results.json",
    "regression_report.json",
    "E158_FINAL_REPORT.md",
    "E158_EXECUTIVE_SUMMARY.md",
    "E158_GATE_MATRIX.json",
    "E158_MANIFEST.json",
    "E158_MERKLE_ROOT.txt",
    "REPRODUCE.md",
]


def _sha256_bytes(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()


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


def verify(bundle_dir: Path) -> tuple[bool, list[dict]]:
    checks = []

    def _chk(name: str, ok: bool, detail: str):
        checks.append({"check": name, "ok": bool(ok), "detail": detail})

    # 1. Required files presence
    missing = [f for f in REQUIRED_ARTIFACTS if not (bundle_dir / f).exists()]
    _chk("required_artifacts_present", not missing, f"missing={missing}" if missing else f"all {len(REQUIRED_ARTIFACTS)} required artifacts present")
    if missing:
        return False, checks

    # 2. Load manifest & check every file hash
    man = json.loads((bundle_dir / "E158_MANIFEST.json").read_text())
    files_map = man.get("files", {})
    bad_hashes = []
    for rel, expected_sha in sorted(files_map.items()):
        fp = bundle_dir / rel
        if not fp.exists():
            bad_hashes.append(f"MISSING:{rel}")
        else:
            actual = _sha256_bytes(fp.read_bytes())
            if actual != expected_sha:
                bad_hashes.append(f"MISMATCH:{rel}")
    _chk("manifest_file_hashes", not bad_hashes and len(files_map) >= 35, f"checked={len(files_map)} bad={bad_hashes[:5]}")

    # 3. Merkle root recomputation
    leaves = [_sha256_bytes(f"{k}:{v}".encode("utf-8")) for k, v in sorted(files_map.items())]
    recomp_root = _merkle_root(leaves)
    stored_root = (bundle_dir / "E158_MERKLE_ROOT.txt").read_text().strip()
    _chk("merkle_root_match", recomp_root == man.get("merkle_root") == stored_root, f"recomputed={recomp_root[:16]} stored={stored_root[:16]}")

    # 4. Ed25519 signature verification
    sig_ok = False
    sig_detail = ""
    try:
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        pub = Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["public_key_hex"]))
        payload = {k: v for k, v in man.items() if k != "signature_hex"}
        canon = json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode("utf-8")
        pub.verify(bytes.fromhex(man["signature_hex"]), canon)
        sig_ok = True
        sig_detail = f"valid Ed25519 signature pubkey={man['public_key_hex'][:16]}"
    except Exception as e:
        sig_detail = f"signature verification failed: {type(e).__name__}: {e}"
    _chk("ed25519_signature", sig_ok, sig_detail)

    # 5. Preregistration SHA-256 commitment
    pre = json.loads((bundle_dir / "hypothesis_preregistration.json").read_text())
    pre_stored = pre.pop("preregistration_sha256", "")
    pre_recomp = _sha256_bytes(json.dumps(pre, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode("utf-8"))
    _chk("preregistration_commitment", pre_stored == pre_recomp and len(pre.get("hypotheses", [])) == 20, f"n_hyp={len(pre.get('hypotheses', []))} hash_match={pre_stored == pre_recomp}")

    # 6. Salt commitments vs revealed salts
    sc = json.loads((bundle_dir / "salt_commitments.json").read_text())
    s_rev = (bundle_dir / "SEALED_SALT_REVEALED.txt").read_text().strip()
    r_rev = (bundle_dir / "REPLICATION_SALT_REVEALED.txt").read_text().strip()
    salt_ok = (_sha256_bytes(s_rev.encode()) == sc["sealed_salt_sha256"]) and (_sha256_bytes(r_rev.encode()) == sc["replication_salt_sha256"]) and (sc["preregistration_sha256"] == pre_stored)
    _chk("salt_commitments_match", salt_ok, f"sealed_ok={_sha256_bytes(s_rev.encode()) == sc['sealed_salt_sha256']} repl_ok={_sha256_bytes(r_rev.encode()) == sc['replication_salt_sha256']}")

    # 7. Organism 12-stage cycle hash-chain verification
    org = json.loads((bundle_dir / "organism_architecture.json").read_text())
    prev = "GENESIS"
    chain_ok = True
    stages = set()
    for rec in org.get("cycle_transitions", []):
        if rec.get("prev_hash") != prev:
            chain_ok = False
            break
        chk_rec = {k: v for k, v in rec.items() if k != "hash"}
        want = _sha256_bytes(json.dumps(chk_rec, sort_keys=True, separators=(",", ":")).encode())
        if rec.get("hash") != want:
            chain_ok = False
            break
        prev = rec["hash"]
        stages.add(rec["stage"])
    _chk("organism_12_stage_cycle_chain", chain_ok and len(stages) == 12, f"stages={len(stages)}/12 chain_ok={chain_ok}")

    # 8. Parent-to-child source lineage & cryptographic diff commitments (IP-protected: ZERO raw source leaked!)
    lin = json.loads((bundle_dir / "successor_lineage.json").read_text())
    chain = lin.get("representative_G0_to_G5_chain", [])
    comm_path = bundle_dir / "source_diffs" / "COMMITMENTS.json"
    comm_doc = json.loads(comm_path.read_text()) if comm_path.exists() else {}
    comm_map = comm_doc.get("diffs", {})
    lin_ok = len(chain) == 6 and comm_path.exists()
    for i in range(1, len(chain)):
        if chain[i]["parent_sha256"] != chain[i - 1]["source_sha256"]:
            lin_ok = False
        df_key = Path(chain[i]["diff_file"]).name if chain[i].get("diff_file") else ""
        if df_key not in comm_map or len(comm_map[df_key].get("diff_sha256", "")) != 64:
            lin_ok = False
    # Enforce Black-Box Core & IP protection: NO proprietary .py, NO raw .diff, NO raw internal genome/patch dicts in public bundle!
    leaked_py = [p.name for p in bundle_dir.rglob("*.py") if p.name != "verify_e158_offline.py"]
    leaked_diff = [p.name for p in bundle_dir.rglob("*.diff")]
    prop_pub = json.loads((bundle_dir / "research_proposer_comparison.json").read_text())
    leaked_genomes = [k for k, v in prop_pub.get("proposers", {}).items() if "champion_genome" in v]
    leaked_patches = [g.get("generation") for g in chain if "genome" in g or "patch" in g]
    ip_clean = (not leaked_py) and (not leaked_diff) and (not leaked_genomes) and (not leaked_patches)
    _chk("successor_parent_lineage_and_diff_commitments", lin_ok and len(comm_map) >= 10, f"chain_len={len(chain)} diff_commitments={len(comm_map)}")
    _chk("black_box_ip_protection_zero_source_leaks", ip_clean, f"leaked_py={leaked_py} leaked_diff={leaked_diff} leaked_genomes={leaked_genomes} leaked_patches={leaked_patches}")

    # 9. Experiment registry consistency, negative results, honest AGI/RSI status
    reg = json.loads((bundle_dir / "experiment_registry.json").read_text())
    neg = json.loads((bundle_dir / "negative_results.json").read_text())
    hyps = reg.get("hypotheses_evaluated", {})
    _chk("hypotheses_20_evaluated", len(hyps) == 20 and reg.get("preregistration_sha256") == pre_stored, f"evaluated={len(hyps)}/20")
    _chk("negative_results_published", neg.get("count", 0) >= 1 and len(neg.get("items", [])) == neg.get("count", 0), f"negative_items={neg.get('count', 0)}")

    # 10. Honest public classification check (AGI: NOT ESTABLISHED, RSI: EXPERIMENTAL)
    status_ok = (org.get("status_declaration", {}).get("AGI") == "NOT ESTABLISHED" and org.get("status_declaration", {}).get("RSI") == "EXPERIMENTAL")
    _chk("honest_agi_rsi_status", status_ok, str(org.get("status_declaration")))

    # 11. Gate matrix check
    gm = json.loads((bundle_dir / "E158_GATE_MATRIX.json").read_text())
    _chk("gate_matrix_24_gates", len(gm.get("gates", {})) == 24, f"gates={len(gm.get('gates', {}))} overall={gm.get('overall')}")

    ok_all = all(c["ok"] for c in checks)
    return ok_all, checks


def main() -> int:
    bdir = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(".")
    ok, checks = verify(bdir)
    for c in checks:
        print(f"[{'PASS' if c['ok'] else 'FAIL'}] {c['check']}: {c['detail']}")
    print("OVERALL:", "PASS" if ok else "FAIL")
    return 0 if ok else 1


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