#!/usr/bin/env python3
"""Standalone zero-CAIN-import verifier for Evolution 79."""
from __future__ import annotations

import base64
import hashlib
import json
import sys
from pathlib import Path
from typing import Any, Dict, List

from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

FIELDS = (
    "mission_specification", "model_runtime_telemetry", "specialist_agent_registry",
    "agent_identities", "collaboration_messages", "collective_benchmark", "external_probe",
    "research_project", "memory_evaluation", "agentic75_matrix", "execution_classes",
    "security_tests", "governance", "distributed_recovery_baseline", "clawx_state",
    "resource_and_cost_accounting", "independent_verification", "artifact_hashes",
    "off_host_anchor", "final_acceptance",
)


def _canon(obj: Any) -> bytes:
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), default=str).encode()


def _sha(obj: Any) -> str:
    if isinstance(obj, (bytes, bytearray)):
        return hashlib.sha256(obj).hexdigest()
    return hashlib.sha256(_canon(obj)).hexdigest()


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


def verify(artifacts: Path) -> Dict[str, Any]:
    required = [
        "phase0_baseline.json", "model_health.json", "agents.json", "benchmark.json",
        "replication.json", "gsm8k_probe.json", "model_scale_comparison.json", "concurrency.json",
        "memory_eval.json", "agentic75.json", "security.json", "governance.json", "research.json",
        "evidence.json", "clawx.json", "e79_master_summary.json", "run_manifest.json", "test_report.json",
    ]
    checks: Dict[str, bool] = {}
    details: Dict[str, Any] = {}

    def req(name: str, condition: bool, detail: Any = None) -> None:
        checks[name] = bool(condition)
        if detail is not None:
            details[name] = detail

    missing = [n for n in required if not (artifacts / n).is_file()]
    req("01_required_artifacts", not missing, {"missing": missing})
    if missing:
        return {"schema": "cain2027.e79.offline_verification_result.v1", "verified": False, "checks": checks, "details": details}

    load = lambda n: json.loads((artifacts / n).read_text())
    p0 = load("phase0_baseline.json"); health = load("model_health.json"); agents = load("agents.json")
    bench = load("benchmark.json"); repl = load("replication.json"); gsm = load("gsm8k_probe.json")
    scale = load("model_scale_comparison.json"); conc = load("concurrency.json"); mem = load("memory_eval.json")
    a75 = load("agentic75.json"); sec = load("security.json"); gov = load("governance.json")
    research = load("research.json"); pkg = load("evidence.json"); clawx = load("clawx.json")
    master = load("e79_master_summary.json"); run = load("run_manifest.json"); tests = load("test_report.json")

    cain_mods = [m for m in sys.modules if m == "cain" or m.startswith("cain.")]
    req("02_zero_cain_imports", not cain_mods, {"cain_modules": cain_mods})
    lm = p0.get("e78_lastmile", {})
    req(
        "03_e78_baseline_reproduced",
        p0.get("e78_final_commit") == "e2851428d2cd7ed9ae46f165e5d9b64c72632cf4"
        and p0.get("e77_verifier", {}).get("passed_count") == 27
        and p0.get("e78_collective_verifier", {}).get("passed_count") == 17
        and lm.get("checks_total") == 41 and lm.get("checks_failed") == 1
        and p0.get("e78_tests", {}).get("tests") == 36
        and p0.get("e78_tests", {}).get("failures", 1) == 0,
        {"e78_final": p0.get("e78_final_commit"), "lastmile": lm},
    )
    req("04_branch_manifest", run.get("branch") == "evolution-79" and run.get("deployed") is False, {"branch": run.get("branch")})

    model = pkg.get("evidence_package_20_fields", {}).get("model_runtime_telemetry") or {}
    req(
        "05_real_local_inference",
        model.get("calls", 0) > 0
        and model.get("output_tokens", 0) > 0
        and model.get("execution_class") == "LOCAL_MODEL_INFERENCE"
        and model.get("cost_usd") == 0.0,
        {"calls": model.get("calls"), "tokens": model.get("total_tokens"), "model": model.get("model")},
    )
    req("06_cloud_not_overclaimed", health.get("cloud", {}).get("execution_class") == "BLOCKED_BILLING", health.get("cloud"))
    req(
        "07_fifteen_signed_agents",
        agents.get("agents_provisioned") == 15 and agents.get("all_signed_and_valid") is True,
        {"agents": agents.get("agents_provisioned")},
    )
    arms = bench.get("arms", {})
    b = arms.get("single_direct", {}).get("accuracy", 0)
    f = arms.get("single_expression", {}).get("accuracy", 0)
    c = arms.get("two_expression_consensus", {}).get("accuracy", 0)
    d = arms.get("four_expression_consensus", {}).get("accuracy", 0)
    e = arms.get("eight_expression_consensus", {}).get("accuracy", 0)
    req(
        "08_benchmark_100_and_collaboration_gain",
        bench.get("tasks_total") == 100 and d > b and d > f,
        {"single": b, "single_expr": f, "two": c, "four": d, "eight": e},
    )
    req(
        "09_held_out_replication",
        repl.get("arms", {}).get("four_expression_consensus", {}).get("accuracy", 0)
        > repl.get("arms", {}).get("single_direct", {}).get("accuracy", 0),
        {"single": repl.get("arms", {}).get("single_direct", {}).get("accuracy"), "four": repl.get("arms", {}).get("four_expression_consensus", {}).get("accuracy")},
    )
    req("10_gsm8k_probe_honest", gsm.get("status") == "PASS" and gsm.get("tasks", 0) <= 10, {"single": gsm.get("single_accuracy"), "four": gsm.get("four_consensus_accuracy")})
    req("11_model_scale_comparison", scale.get("execution_class") == "LOCAL_MODEL_INFERENCE" and scale.get("tasks") == 10, {"accuracy": scale.get("accuracy")})
    req("12_concurrency_batched_honest", set(conc) == {"1", "2", "4", "8", "16"} and all(v.get("os_agent_processes") == 0 for v in conc.values()), {k: v.get("throughput_prompts_per_sec") for k, v in conc.items()})
    loc = mem.get("locomo", {}).get("with_context", {})
    mag = mem.get("memoryagentbench", {}).get("with_context", {})
    req(
        "13_memory_answer_accuracy",
        loc.get("evaluated", 0) >= 50
        and (mag.get("evaluated", 0) >= 30 or mem.get("memoryagentbench", {}).get("status") == "BLOCKED"),
        {"locomo_exact": loc.get("exact_match"), "mag_exact": mag.get("exact_match"), "mag_status": mem.get("memoryagentbench", {}).get("status")},
    )
    req("14_agentic75_matrix", a75.get("standalone_executed") == 75 and a75.get("model_backed") == 0, {"executed": a75.get("standalone_executed")})
    req(
        "15_security_and_governance",
        sec.get("prompt_injection", {}).get("cases", 0) >= 5
        and sec.get("prompt_injection", {}).get("tool_executions") == 0
        and sec.get("model_call_blocked_by_kill_switch") is True
        and gov.get("all_10_levels_verified") is True,
        {"injection_cases": sec.get("prompt_injection", {}).get("cases"), "blocked_call": sec.get("model_call_blocked_by_kill_switch")},
    )
    req(
        "16_research_replicated",
        research.get("scientific_discovery") == "NOT_CLAIMED"
        and research.get("epistemic_ledger", {}).get("REPRODUCED_RESULT", {}).get("direction_replicated") is True,
        research.get("deltas"),
    )

    bundle = pkg.get("evidence_package_20_fields", {})
    manifest = pkg.get("manifest", {})
    missing_fields = [x for x in FIELDS if x not in bundle]
    leaves = [_sha({k: bundle[k]}) for k in FIELDS if k in bundle]
    merkle = _merkle(leaves)
    sig_ok = False
    rot_ok = False
    try:
        pub = Ed25519PublicKey.from_public_bytes(base64.b64decode(pkg["public_key_b64"]))
        pub.verify(base64.b64decode(pkg["signature_b64"]), _canon(manifest))
        sig_ok = True
        rot = manifest["key_rotation"]
        stmt = {"event": rot["event"], "old_public_key_b64": rot["old_public_key_b64"], "new_public_key_b64": rot["new_public_key_b64"], "rotated_at_utc": rot["rotated_at_utc"]}
        old = Ed25519PublicKey.from_public_bytes(base64.b64decode(rot["old_public_key_b64"]))
        new = Ed25519PublicKey.from_public_bytes(base64.b64decode(rot["new_public_key_b64"]))
        old.verify(base64.b64decode(rot["signature_by_old_key_b64"]), _canon(stmt))
        new.verify(base64.b64decode(rot["signature_by_new_key_b64"]), _canon(stmt))
        rot_ok = True
    except Exception:
        pass
    req("17_evidence_20_fields_and_signature", not missing_fields and _sha(bundle) == manifest.get("bundle_sha256") and merkle == manifest.get("merkle_root") and sig_ok and rot_ok, {"missing": missing_fields, "signature": sig_ok})
    failures = []
    for name, digest in (manifest.get("artifact_hashes") or {}).items():
        p = artifacts / name
        if not p.is_file() or hashlib.sha256(p.read_bytes()).hexdigest() != digest:
            failures.append(name)
    req("18_artifact_hashes", len(manifest.get("artifact_hashes") or {}) >= 10 and not failures, {"failures": failures, "count": len(manifest.get("artifact_hashes") or {})})
    checks_bundle = bundle.get("independent_verification", {}).get("checks", {})
    req("19_acceptance_evidence_derived", bundle.get("final_acceptance", {}).get("state") == "DEVELOPMENT_EVIDENCE_ACCEPTED" and all(checks_bundle.values()), {"state": bundle.get("final_acceptance", {}).get("state"), "failed": [k for k, v in checks_bundle.items() if not v]})
    req("20_clawx_local_15_views", clawx.get("deployment_status") == "LOCAL_BACKEND_ONLY_NOT_DEPLOYED" and clawx.get("view_count") == 15 and clawx.get("all_15_views_authenticated") is True and clawx.get("tampered_evidence_rejected") is True, {"deployment": clawx.get("deployment_status")})
    score = master.get("scorecard", {})
    req("21_scorecard_honest", len(score.get("dimensions", {})) == 13 and not str(score.get("grade", "")).startswith("A") and float(score.get("composite", 10)) < 9.0 and master.get("production_ready") is False, {"grade": score.get("grade"), "score": score.get("composite")})
    req("22_tests_pass", tests.get("tests", 0) >= 8 and tests.get("failures", 1) == 0 and tests.get("errors", 1) == 0, {"tests": tests.get("tests")})

    passed = sum(1 for v in checks.values() if v)
    return {
        "schema": "cain2027.e79.offline_verification_result.v1",
        "verified": passed == len(checks),
        "passed_count": passed,
        "total_checks": len(checks),
        "checks": checks,
        "details": details,
        "bundle_sha256": manifest.get("bundle_sha256"),
        "merkle_root": merkle,
    }


def main() -> int:
    target = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).resolve().parents[2] / "artifacts/e79"
    result = verify(target)
    print(json.dumps(result, indent=2, sort_keys=True))
    return 0 if result.get("verified") else 1


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