#!/usr/bin/env python3
"""Standalone Evolution 81 evidence verifier.

Imports no CAIN code. Only the Python standard library and `cryptography`.
Verifies: manifest signature, file set and hashes, Merkle root, event hash chain and
per-event signatures, required event fields, task/effect consistency, checkpoint chain and
mission verdict consistency.

Usage: python3 verify_e81_offline.py <bundle_dir> [--pinned-key <base64 public key>]
Exit code 0 only when every check passes.
"""
from __future__ import annotations

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

from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey


def canonical(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()
    if isinstance(obj, str):
        return hashlib.sha256(obj.encode()).hexdigest()
    return hashlib.sha256(canonical(obj)).hexdigest()


def verify_sig(pub_b64: str, payload: Any, sig_b64: str) -> bool:
    try:
        raw = base64.b64decode(pub_b64)
        pub = Ed25519PublicKey.from_public_bytes(raw)
        pub.verify(base64.b64decode(sig_b64), canonical(payload))
        return True
    except (InvalidSignature, ValueError, TypeError):
        return False


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


REQUIRED_EVENT_FIELDS = ("event_id", "agent_id", "mission_id", "utc", "host", "authorization_ref",
                         "execution_ref", "evidence_digest", "provenance", "verification_status",
                         "signature_b64", "agent_public_key_b64")


def verify(path: Path, pinned: str = "") -> Dict[str, Any]:
    failures: List[str] = []
    checks: Dict[str, bool] = {}
    p = Path(path)
    mpath = p / "manifest.json"
    if not mpath.is_file():
        return {"ok": False, "checks": {"manifest_present": False}, "failures": ["MANIFEST_MISSING"]}
    try:
        manifest = json.loads(mpath.read_text())
    except Exception as exc:
        return {"ok": False, "checks": {}, "failures": [f"MANIFEST_UNPARSEABLE:{exc}"]}
    checks["manifest_present"] = True

    # 1. signature
    body = {k: v for k, v in manifest.items() if k != "signature_b64"}
    signer = manifest.get("signer", {})
    pub = signer.get("public_key_b64", "")
    checks["manifest_signature"] = verify_sig(pub, body, manifest.get("signature_b64", ""))
    if not checks["manifest_signature"]:
        failures.append("MANIFEST_SIGNATURE_INVALID")
    if pinned:
        checks["signer_matches_pinned_key"] = (pub == pinned)
        if not checks["signer_matches_pinned_key"]:
            failures.append("SIGNER_NOT_PINNED_KEY")
    else:
        checks["signer_matches_pinned_key"] = True  # not applicable; reported as UNPINNED

    # 2. files
    listed = {f["path"]: f for f in manifest.get("files", [])}
    actual = {str(f.relative_to(p)): f for f in p.rglob("*") if f.is_file() and f.name != "manifest.json"}
    missing = [r for r in listed if r not in actual]
    unlisted = [r for r in actual if r not in listed]
    bad = [r for r, f in listed.items() if r in actual and sha(actual[r].read_bytes()) != f["sha256"]]
    checks["files_present"] = not missing
    checks["no_unlisted_files"] = not unlisted
    checks["file_hashes"] = not bad
    for x in missing:
        failures.append(f"FILE_MISSING:{x}")
    for x in unlisted:
        failures.append(f"FILE_UNLISTED:{x}")
    for x in bad:
        failures.append(f"FILE_HASH_MISMATCH:{x}")

    # 3. merkle
    leaves = [f["sha256"] for f in manifest.get("files", [])]
    checks["merkle_root"] = merkle(leaves) == manifest.get("merkle_root")
    if not checks["merkle_root"]:
        failures.append("MERKLE_ROOT_MISMATCH")

    # 4. events
    ev_path = p / "events.json"
    events = json.loads(ev_path.read_text()) if ev_path.is_file() else []
    prev = "0" * 64
    chain = True
    sigs = True
    fields = True
    for i, r in enumerate(events):
        if r.get("prev") != prev:
            chain = False
            failures.append(f"EVENT_PREV_MISMATCH:{i}")
            break
        if sha({k: v for k, v in r.items() if k != "hash"}) != r.get("hash"):
            chain = False
            failures.append(f"EVENT_HASH_MISMATCH:{i}")
            break
        if not verify_sig(r.get("agent_public_key_b64", ""),
                          {k: r[k] for k in ("event_id", "mission_id", "agent_id", "action",
                                             "evidence_digest", "prev")},
                          r.get("signature_b64", "")):
            sigs = False
            failures.append(f"EVENT_SIGNATURE_INVALID:{i}")
            break
        if any(k not in r for k in REQUIRED_EVENT_FIELDS):
            fields = False
            failures.append(f"EVENT_FIELD_MISSING:{i}")
            break
        prev = r["hash"]
    checks["event_chain"] = chain
    checks["event_signatures"] = sigs
    checks["event_required_fields"] = fields
    checks["event_count_matches_manifest"] = len(events) == int(manifest.get("event_count", -1))

    # 5. tasks / effects
    tasks = json.loads((p / "tasks.json").read_text()) if (p / "tasks.json").is_file() else []
    effects = json.loads((p / "effects.json").read_text()) if (p / "effects.json").is_file() else []
    idems = [e.get("idem") for e in effects]
    done = [t for t in tasks if t.get("state") == "DONE"]
    checks["effects_unique"] = len(idems) == len(set(idems))
    checks["effects_match_done_tasks"] = len(effects) == len(done)
    checks["task_idem_matches_effect"] = all(
        any(e.get("idem") == t.get("idem") and e.get("task_id") == t.get("id") for e in effects)
        for t in done)
    if not checks["effects_unique"]:
        failures.append("DUPLICATE_EFFECT_IDEM")
    if not checks["task_idem_matches_effect"]:
        failures.append("TASK_EFFECT_MISMATCH")

    # 6. checkpoints
    cps = json.loads((p / "checkpoints.json").read_text()) if (p / "checkpoints.json").is_file() else []
    prev = "0" * 64
    cp_ok = True
    for c in sorted(cps, key=lambda x: x.get("seq", 0)):
        body_cp = {"mission_id": c.get("mission_id"), "seq": c.get("seq"),
                   "state": c.get("state"), "prev": prev, "utc": c.get("utc")}
        if c.get("prev_hash") != prev or sha(body_cp) != c.get("hash"):
            cp_ok = False
            failures.append(f"CHECKPOINT_CHAIN_BROKEN:{c.get('seq')}")
            break
        prev = c["hash"]
    checks["checkpoint_chain"] = cp_ok

    # 7. verdict consistency
    mission = json.loads((p / "mission.json").read_text()) if (p / "mission.json").is_file() else {}
    state = mission.get("state")
    checks["mission_state_present"] = bool(state)
    checks["manifest_counts_match"] = (
        int(manifest.get("task_count", -1)) == len(tasks)
        and int(manifest.get("effect_count", -1)) == len(effects))
    if state == "COMPLETED":
        checks["completed_missions_have_all_tasks_done"] = all(t.get("state") == "DONE" for t in tasks)
    else:
        checks["completed_missions_have_all_tasks_done"] = True

    return {"schema": "cain2027.e81.offline_verification.v1",
            "ok": not failures, "checks": checks, "failures": failures,
            "files_checked": len(listed), "events": len(events), "tasks": len(tasks),
            "effects": len(effects), "checkpoints": len(cps),
            "merkle_root": manifest.get("merkle_root"),
            "signer_fingerprint": manifest.get("signer", {}).get("key_fingerprint"),
            "pinned_key": bool(pinned),
            "verdict": manifest.get("verdict"), "evidence_class": manifest.get("evidence_class"),
            "independence": ("SELF_GENERATED_KEY" if not pinned else "PINNED_KEY") +
                            "; no independent witness or third-party audit"}


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("bundle")
    ap.add_argument("--pinned-key", default="")
    args = ap.parse_args()
    out = verify(Path(args.bundle), args.pinned_key)
    print(json.dumps(out, indent=1, sort_keys=True))
    return 0 if out["ok"] else 1


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