#!/usr/bin/env python3
"""Standalone offline verifier for CAIN-2027 Evolution 77.

This verifier imports zero `cain.*` modules. It uses the Python standard library plus
`cryptography` for Ed25519 verification. It checks measured fields and recomputes hashes,
the RFC 6962 field tree, the artifact digests and the signed manifest.

It does NOT prove that a remote host exists, that a cloud model ran, or that a third party
audited the code. Those limits are encoded in the checks.

Usage:
    python3 scripts/evolution77/verify_e77_offline.py [artifacts/e77]
"""
from __future__ import annotations

import argparse
import base64
import hashlib
import json
import sys
from pathlib import Path
from typing import Any, Dict, List, Mapping, Optional, Sequence

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

MANDATORY_17_FIELDS = (
    "mission_identifier",
    "mission_specification_hash",
    "parent_mission",
    "agent_identities",
    "delegation_lineage",
    "capability_identifiers",
    "model_provider_metadata",
    "authorization_records",
    "execution_event_history",
    "tool_invocation_records",
    "checkpoints",
    "result_artifacts",
    "independent_verification_results",
    "resource_and_cost_accounting",
    "failure_and_recovery_events",
    "kill_switch_history",
    "final_acceptance_state",
)


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


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


def _sha256_file(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def _merkle_root_hex(leaves: Sequence[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: List[bytes] = []
        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 _load(path: Path) -> Dict[str, Any]:
    return json.loads(path.read_text(encoding="utf-8"))


def verify(artifacts_dir: Path) -> Dict[str, Any]:
    checks: Dict[str, bool] = {}
    details: Dict[str, Any] = {}

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

    required_files = [
        "phase0_forensic_baseline.json",
        "phase1_swarm_os.json",
        "phase3_collective_memory.json",
        "phase4_agentic75.json",
        "phase5_model_intelligence.json",
        "phase6_sandbox_fabric.json",
        "phase7_kill_switch.json",
        "phase8_mission_intelligence.json",
        "phase9_scale_and_endurance.json",
        "phase10_clawx_command_center.json",
        "phase12_release_gate.json",
        "signed_mission_evidence_bundle.json",
        "e77_master_summary.json",
        "run_manifest.json",
    ]
    missing = [n for n in required_files if not (artifacts_dir / n).is_file()]
    require("01_required_artifacts_present", not missing, {"missing": missing})
    if missing:
        return {
            "schema": "cain2027.e77.offline_verification_result.v2",
            "verified": False,
            "checks": checks,
            "details": details,
        }

    p0 = _load(artifacts_dir / "phase0_forensic_baseline.json")
    p1 = _load(artifacts_dir / "phase1_swarm_os.json")
    p3 = _load(artifacts_dir / "phase3_collective_memory.json")
    p4 = _load(artifacts_dir / "phase4_agentic75.json")
    p5 = _load(artifacts_dir / "phase5_model_intelligence.json")
    p6 = _load(artifacts_dir / "phase6_sandbox_fabric.json")
    p7 = _load(artifacts_dir / "phase7_kill_switch.json")
    p9 = _load(artifacts_dir / "phase9_scale_and_endurance.json")
    p10 = _load(artifacts_dir / "phase10_clawx_command_center.json")
    p12 = _load(artifacts_dir / "phase12_release_gate.json")
    pkg = _load(artifacts_dir / "signed_mission_evidence_bundle.json")
    master = _load(artifacts_dir / "e77_master_summary.json")
    run_manifest = _load(artifacts_dir / "run_manifest.json")

    cain_mods = [m for m in sys.modules if m == "cain" or m.startswith("cain.")]
    require("02_zero_cain_imports", not cain_mods, {"cain_modules_loaded": cain_mods})
    branches = p0.get("git_lineage", {}).get("preserved_branches", {})
    require(
        "03_git_baseline_reproduced",
        branches.get("evolution-76", {}).get("actual_commit")
        == "badc320c41a38b5c76266d044aacff4c79ad96e5"
        and branches.get("evolution-75", {}).get("actual_commit")
        == "bb5cc00eabfa403fb0a0898c397a690053279c6e"
        and p0.get("e76_offline_verifier", {}).get("verified") is True,
        {
            "e76_verifier": p0.get("e76_offline_verifier", {}).get("passed_count"),
            "e76_total": p0.get("e76_offline_verifier", {}).get("total_checks"),
        },
    )
    require(
        "04_run_manifest_matches_baseline",
        run_manifest.get("baseline_commit") == "badc320c41a38b5c76266d044aacff4c79ad96e5"
        and master.get("baseline_e76_commit") == "badc320c41a38b5c76266d044aacff4c79ad96e5"
        and run_manifest.get("branch") == "evolution-77",
        {"run_commit": run_manifest.get("commit"), "branch": run_manifest.get("branch")},
    )

    attenuation = p1.get("authority_attenuation") or {}
    require(
        "05_swarm_attenuation_and_fencing",
        bool(p1.get("all_11_mandatory_attributes_present"))
        and bool(p1.get("all_5_topologies_exercised"))
        and bool(attenuation.get("capability_escalation_blocked"))
        and bool(attenuation.get("budget_escalation_blocked"))
        and bool((p1.get("lease_and_fencing") or {}).get("stale_worker_message_blocked")),
        attenuation,
    )

    acct = p9.get("five_state_task_accounting") or {}
    bench = p9.get("benchmarks_a_to_j") or {}
    persistence = bench.get("A_task_record_persistence") or {}
    concurrent = bench.get("C_concurrent_task_execution") or {}
    recovery = bench.get("E_distributed_worker_recovery") or {}
    sigkill = recovery.get("subprocess_sigkill_drill") or {}
    coverage = p9.get("agentic75_execution_coverage") or {}
    ks_probe = bench.get("F_kill_switch_boundary_probe") or {}
    campaign = (p9.get("endurance_campaigns") or {}).get("e77_live_wallclock_campaign") or {}
    require(
        "06_million_rows_are_rows_not_execution",
        persistence.get("persisted_1m_total_rows") == 1_000_000
        and persistence.get("mode") == "LOCAL_MEASURED_REAL_INSERTS"
        and int(acct.get("tasks_persisted", 0)) >= 1_000_000
        and int(acct.get("tasks_executed", 0)) < 1000,
        {"persisted": acct.get("tasks_persisted"), "executed": acct.get("tasks_executed")},
    )
    require(
        "07_real_task_execution_and_verification",
        int(bench.get("F_mission_completion_reliability", {}).get("sequential_tasks_independently_verified", 0)) == 250
        and int(concurrent.get("tasks_independently_verified", 0)) == 100
        and coverage.get("all_75_covered") is True
        and int(coverage.get("distinct_skus_executed", 0)) == 75,
        {
            "sequential_verified": bench.get("F_mission_completion_reliability", {}).get("sequential_tasks_independently_verified"),
            "concurrent_verified": concurrent.get("tasks_independently_verified"),
            "distinct_skus": coverage.get("distinct_skus_executed"),
        },
    )
    require(
        "08_concurrency_is_measured_not_claimed",
        concurrent.get("mode") == "MEASURED_8_THREAD_REAL_ENGINE_EXECUTION"
        and int(concurrent.get("worker_threads", 0)) == 8
        and p9.get("benchmarks_a_to_j", {})
        .get("D_concurrent_specialist_agents", {})
        .get("one_thousand_os_processes")
        == "BLOCKED_HOST_CAPACITY_NOT_TESTED",
        {"worker_threads": concurrent.get("worker_threads")},
    )
    require(
        "09_sigkill_recovery_zero_duplicate_side_effects",
        sigkill.get("killed_by_sigkill") is True
        and sigkill.get("duplicate_external_side_effects") == 0
        and sigkill.get("independently_verified_after_recovery") is True,
        sigkill,
    )
    require(
        "10_kill_switch_stops_queued_task",
        ks_probe.get("queued_task_blocked") is True
        and ks_probe.get("stale_worker_after_clear_blocked") is True,
        {"reason": ks_probe.get("blocked_reason")},
    )
    require(
        "11_endurance_is_honestly_bounded",
        campaign.get("status") == "PASS"
        and float(campaign.get("actual_elapsed_seconds", 0.0)) >= 59.5
        and (p9.get("endurance_campaigns") or {}).get("1h_actual_elapsed", {}).get("status") in {"BLOCKED", "PARTIAL"},
        {"campaign_seconds": campaign.get("actual_elapsed_seconds"), "campaign_status": campaign.get("status")},
    )

    require(
        "12_memory_aes_gcm_and_isolation",
        p3.get("encryption_algorithm") == "AES-256-GCM"
        and p3.get("mandatory_11_fields_enforced") is True
        and (p3.get("adversarial_memory_tests") or {}).get("poisoned_memory_detected_and_rejected") is True
        and (p3.get("adversarial_memory_tests") or {}).get("unauthorized_cross_tenant_access_blocked") is True
        and (p3.get("adversarial_memory_tests") or {}).get("unauthorized_cross_mission_retrieval_blocked") is True,
        {"algorithm": p3.get("encryption_algorithm")},
    )
    maturity = p4.get("maturity_taxonomy") or {}
    require(
        "13_agentic75_real_mission_integration",
        maturity.get("mission_integrated") == 75
        and maturity.get("independently_verified") == 75
        and p4.get("all_75_mission_tasks_independently_verified") is True
        and maturity.get("transferred_to_unfamiliar_tasks") == 0,
        maturity,
    )

    local = p5.get("direct_local_hf_execution") or {}
    require(
        "14_local_model_really_executed",
        p5.get("local_inference_executed") is True
        and local.get("provider_class") == "REAL_LOCAL_WEIGHTS"
        and int(local.get("output_tokens", 0)) > 0
        and float(local.get("latency_ms", 0.0)) > 0
        and bool(local.get("output_text")),
        {
            "model": local.get("model"),
            "output_tokens": local.get("output_tokens"),
            "latency_ms": local.get("latency_ms"),
        },
    )
    require(
        "15_cloud_providers_not_faked",
        p5.get("providers_with_live_execution") == 1
        and (p5.get("missing_key_explicit_blocked") or {}).get("status") == "BLOCKED",
        {"providers_with_live_execution": p5.get("providers_with_live_execution")},
    )

    sandbox = p6.get("valid_sandbox_execution") or {}
    sandbox_adv = p6.get("adversarial_tests") or {}
    require(
        "16_sandbox_boundary_is_real_and_labelled",
        sandbox.get("effective_backend") == "BWRAP_USER_NET_PID_NAMESPACE"
        and sandbox.get("hardware_isolated_vm") is False
        and sandbox_adv.get("network_egress_blocked") is True
        and sandbox_adv.get("host_secret_inheritance_blocked") is True
        and sandbox_adv.get("path_traversal_escape_blocked") is True,
        {"effective_backend": sandbox.get("effective_backend")},
    )

    require(
        "17_identity_tokens_are_signed",
        p7.get("identity_signature_verified") is True
        and p7.get("tampered_identity_rejected") is True
        and p7.get("expired_identity_rejected") is True
        and p7.get("mandatory_e62_identity_enforced") is True,
        {},
    )
    require(
        "18_kill_switch_all_levels_and_scenarios",
        p7.get("all_8_levels_verified") is True
        and p7.get("all_8_active_scenarios_verified") is True
        and p7.get("model_self_override_blocked") is True,
        {},
    )

    bundle = pkg.get("evidence_package_17_fields") or {}
    manifest = pkg.get("manifest") or {}
    missing_fields = [f for f in MANDATORY_17_FIELDS if f not in bundle]
    require("19_seventeen_evidence_fields", not missing_fields, {"missing": missing_fields})
    bundle_sha = _sha256_obj(bundle)
    leaves = [_sha256_obj({k: bundle[k]}) for k in MANDATORY_17_FIELDS]
    merkle = _merkle_root_hex(leaves)
    require(
        "20_bundle_and_merkle_root",
        bundle_sha == manifest.get("bundle_sha256") and merkle == manifest.get("merkle_root"),
        {"bundle_sha256": bundle_sha, "merkle_root": merkle},
    )
    chain_ok = True
    prev = "0" * 64
    for event in bundle.get("execution_event_history") or []:
        event_copy = {k: v for k, v in event.items() if k not in ("prev_hash", "event_hash")}
        expected = _sha256_obj({"prev_hash": prev, "event": event_copy})
        if event.get("prev_hash") != prev or event.get("event_hash") != expected:
            chain_ok = False
            break
        prev = expected
    require("21_event_hash_chain", chain_ok and len(bundle.get("execution_event_history") or []) >= 6)

    signature_ok = False
    rotation_ok = False
    try:
        pub = Ed25519PublicKey.from_public_bytes(base64.b64decode(pkg["public_key_b64"]))
        pub.verify(base64.b64decode(pkg["signature_b64"]), _canonical_bytes(manifest))
        signature_ok = True
        rotation = manifest.get("key_rotation") or {}
        rotation_statement = {
            "event": rotation["event"],
            "old_public_key_b64": rotation["old_public_key_b64"],
            "new_public_key_b64": rotation["new_public_key_b64"],
            "rotated_at_utc": rotation["rotated_at_utc"],
        }
        old_pub = Ed25519PublicKey.from_public_bytes(base64.b64decode(rotation["old_public_key_b64"]))
        new_pub = Ed25519PublicKey.from_public_bytes(base64.b64decode(rotation["new_public_key_b64"]))
        old_pub.verify(base64.b64decode(rotation["signature_by_old_key_b64"]), _canonical_bytes(rotation_statement))
        new_pub.verify(base64.b64decode(rotation["signature_by_new_key_b64"]), _canonical_bytes(rotation_statement))
        rotation_ok = True
    except Exception:  # noqa: BLE001
        signature_ok = False
        rotation_ok = False
    require("22_ed25519_and_key_rotation", signature_ok and rotation_ok)

    artifact_failures: List[str] = []
    for name, expected in (manifest.get("artifact_sha256") or {}).items():
        path = artifacts_dir / name
        if not path.is_file():
            artifact_failures.append(f"{name}:MISSING")
        elif _sha256_file(path) != expected:
            artifact_failures.append(f"{name}:MISMATCH")
    require(
        "23_artifact_hashes_match_raw_results",
        len(manifest.get("artifact_sha256") or {}) >= 8 and not artifact_failures,
        {"failures": artifact_failures, "count": len(manifest.get("artifact_sha256") or {})},
    )
    acceptance = (bundle.get("independent_verification_results") or {}).get("acceptance_checks") or {}
    require(
        "24_acceptance_is_evidence_derived",
        bundle.get("final_acceptance_state") == "VERIFIED_ACCEPTED"
        and manifest.get("final_acceptance_state") == "VERIFIED_ACCEPTED"
        and bool(acceptance)
        and all(acceptance.values()),
        acceptance,
    )

    require(
        "25_clawx_is_local_and_authenticated",
        p10.get("deployment_status") == "LOCAL_BACKEND_ONLY_NOT_DEPLOYED"
        and p10.get("static_html_is_not_integration") is True
        and p10.get("unauthenticated_access_blocked") is True
        and p10.get("cross_tenant_access_blocked") is True
        and p10.get("tampered_evidence_rejected_by_viewer") is True
        and p10.get("all_11_views_authenticated_and_rendered") is True,
        {"deployment_status": p10.get("deployment_status")},
    )
    require(
        "26_anchor_is_labelled_partial",
        (master.get("off_host_anchor") or {}).get("off_host_anchored") in {True, False}
        and (master.get("off_host_anchor") or {}).get("anchor_status")
        == "PARTIAL_MUTABLE_REMOTE_FILE_SAME_ADMIN_DOMAIN",
        {"anchor_status": (master.get("off_host_anchor") or {}).get("anchor_status")},
    )

    require(
        "27_scorecard_is_not_self_awarded",
        len(p12.get("scorecard_13_dimensions") or {}) == 13
        and len(p12.get("forensic_24_answers") or {}) == 24
        and p12.get("self_awarded_a_plus_plus_plus_plus") is False
        and not str(p12.get("overall_honest_grade", "")).startswith("A")
        and float(p12.get("composite_score", 10.0)) < 9.0,
        {"grade": p12.get("overall_honest_grade"), "score": p12.get("composite_score")},
    )

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


def main() -> int:
    target = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).resolve().parents[2] / "artifacts/e77"
    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())
