#!/usr/bin/env python3
"""Independent CAIN-2027 mission verifier. Standard library + cryptography; imports no CAIN code.

Re-derives the journal chain, transition legality, completion proof, signed tickets/grants, action bindings and
deliverable digests. A self-generated evidence key proves internal consistency and tamper detection, not a third-party
identity.
"""
from __future__ import annotations

import argparse
import base64
import hashlib
import json
import math
import os
import sys

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

SCHEMA = "cain74.mission.evidence.bundle.v1"
DOMAIN = "cain74.mission.manifest.v1"
D_GRANT = "cain66.child.grant.v1"
D_TICKET = "cain68.op.ticket.v1"

TRANSITIONS = {
    "CREATED": {"UNDERSTANDING", "REJECTED", "CANCELLED"},
    "UNDERSTANDING": {"PLANNING", "REJECTED", "FAILED", "CANCELLED"},
    "PLANNING": {"PLANNED", "REPLANNING", "FAILED", "CANCELLED"},
    "PLANNED": {"CAPABILITY_SELECTION", "REPLANNING", "CANCELLED"},
    "CAPABILITY_SELECTION": {"AUTHORIZATION_PENDING", "PLANNING", "BLOCKED", "CANCELLED"},
    "AUTHORIZATION_PENDING": {"AUTHORIZED", "REJECTED", "BLOCKED", "CANCELLED"},
    "AUTHORIZED": {"EXECUTING", "CANCELLED", "BLOCKED"},
    "EXECUTING": {"OBSERVING", "RECOVERING", "BLOCKED", "WAITING", "FAILED", "CANCELLED"},
    "OBSERVING": {"VERIFYING", "EXECUTING", "REPLANNING", "RECOVERING", "BLOCKED", "FAILED", "CANCELLED"},
    "VERIFYING": {"COMPLETED", "FAILED", "REPLANNING", "IMPROVEMENT_PENDING", "CANCELLED"},
    "BLOCKED": {"REPLANNING", "RECOVERING", "FAILED", "REJECTED", "CANCELLED"},
    "REPLANNING": {"PLANNING", "AUTHORIZATION_PENDING", "FAILED", "CANCELLED"},
    "RECOVERING": {"EXECUTING", "VERIFYING", "FAILED", "CANCELLED"},
    "WAITING": {"EXECUTING", "REPLANNING", "FAILED", "CANCELLED"},
    "IMPROVEMENT_PENDING": {"COMPLETED", "PLANNING", "FAILED"},
    "COMPLETED": {"ARCHIVED"}, "REJECTED": {"ARCHIVED"}, "CANCELLED": {"ARCHIVED"},
    "FAILED": {"ARCHIVED", "REPLANNING"}, "ARCHIVED": set(),
}


def norm(o):
    if isinstance(o, float):
        if not math.isfinite(o):
            raise ValueError("NON_FINITE")
        return int(o) if o.is_integer() else o
    if isinstance(o, dict):
        return {str(k): norm(v) for k, v in o.items()}
    if isinstance(o, (list, tuple)):
        return [norm(v) for v in o]
    return o


def canon(o):
    return json.dumps(norm(o), sort_keys=True, separators=(",", ":"), ensure_ascii=True, default=str).encode()


def sha(o):
    return hashlib.sha256(canon(o)).hexdigest()


def journal_canon(o):
    # MissionJournal._canon does not normalize integral floats; use the exact journal form here.
    return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=True, default=str).encode()


def sha_file(p):
    return hashlib.sha256(open(p, "rb").read()).hexdigest()


def verify_sig(pub, sig, domain, body):
    try:
        ed25519.Ed25519PublicKey.from_public_bytes(base64.b64decode(pub)).verify(
            base64.b64decode(sig), domain.encode() + b"\0" + canon(body))
        return True
    except (InvalidSignature, ValueError, TypeError):
        return False


def read(p):
    return json.loads(open(p, "rb").read().decode())


def main(argv=None) -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("bundle")
    ap.add_argument("--json", action="store_true")
    a = ap.parse_args(argv)
    b = os.path.abspath(a.bundle)
    problems, checks = [], []
    mp = os.path.join(b, "manifest.json")
    if not os.path.isfile(mp):
        print(json.dumps({"ok": False, "problems": ["manifest_missing"]}))
        return 1
    m = read(mp)
    if m.get("schema") != SCHEMA:
        problems.append("schema_invalid")
    body = {k: v for k, v in m.items() if k != "signature"}
    pinned = read(os.path.join(b, "pinned-key.json")) if os.path.isfile(os.path.join(b, "pinned-key.json")) else {}
    pub = str(pinned.get("pub") or body.get("pub") or "")
    if not pub or not verify_sig(pub, str(m.get("signature") or ""), DOMAIN, body):
        problems.append("manifest_signature_invalid")
    else:
        checks.append("manifest_signature")

    files = m.get("files") or {}
    for rel, meta in files.items():
        p = os.path.join(b, rel)
        if not os.path.isfile(p):
            problems.append(f"file_missing:{rel}")
        elif sha_file(p) != meta.get("sha256"):
            problems.append(f"digest_mismatch:{rel}")
    checks.append(f"files_checked:{len(files)}")

    def data(rel):
        p = os.path.join(b, rel)
        return read(p) if os.path.isfile(p) else None

    # journal chain
    events = []
    jp = os.path.join(b, "journal.jsonl")
    if os.path.isfile(jp):
        for line in open(jp):
            if line.strip():
                events.append(json.loads(line))
    prev = "0" * 64
    chain_ok = True
    for e in events:
        body_e = {k: e.get(k) for k in ("seq", "event_id", "mission_id", "kind", "actor", "occurred_at", "prev_hash", "body")}
        if e.get("prev_hash") != prev or hashlib.sha256(journal_canon(body_e)).hexdigest() != e.get("digest"):
            chain_ok = False
            problems.append(f"journal_break:{e.get('seq')}")
            break
        prev = e.get("digest")
    checks.append(f"journal_chain:{len(events)}")
    if not chain_ok:
        problems.append("journal_chain_invalid")

    # transitions
    state = "CREATED"
    allow_events = [e for e in events if e.get("kind") == "AUTHORIZATION"
                    and (e.get("body") or {}).get("decision") == "ALLOW"]
    for e in events:
        if e.get("kind") != "STATE":
            continue
        to = (e.get("body") or {}).get("to")
        if to not in TRANSITIONS.get(state, set()):
            problems.append(f"illegal_transition:{state}->{to}")
        if to == "EXECUTING" and not allow_events:
            problems.append("executing_without_allow")
        state = to
    checks.append(f"final_state:{state}")
    if m.get("state") != state:
        problems.append(f"manifest_state_mismatch:{m.get('state')}!={state}")

    # verification / completion
    contract = data("contract.json") or {}
    ver = data("verification.json") or []
    criteria = list(contract.get("success_criteria") or [])
    verified_criteria = {v.get("criterion") for v in ver if v.get("passed") and v.get("independent")}
    if state == "COMPLETED":
        if not ver or not all(v.get("passed") for v in ver):
            problems.append("completed_without_all_verifications_passed")
        if not any(v.get("independent") for v in ver):
            problems.append("completed_without_independent_verifier")
        missing = [c for c in criteria if c not in verified_criteria]
        if missing:
            problems.append(f"criteria_not_independently_verified:{len(missing)}")
    checks.append(f"verifications:{len(ver)}")

    # contract invariants
    if (contract.get("model_policy") or {}).get("self_authorization") != "deny":
        problems.append("model_self_authorization_present")
    if (contract.get("memory_policy") or {}).get("grants_authority"):
        problems.append("memory_grants_authority_present")

    # grant + tickets
    authority_pub = str(m.get("authority_pub") or "")
    grant = data("grant.json") or {}
    if grant:
        gb = grant.get("body") or {}
        gbody = {k: v for k, v in gb.items() if k != "signature"}
        if not verify_sig(authority_pub, str(gb.get("signature") or ""), D_GRANT, gbody):
            problems.append("grant_signature_invalid")
        if gb.get("mission_id") != m.get("mission_id"):
            problems.append("grant_mission_mismatch")
        checks.append("grant_signature")
    else:
        problems.append("grant_missing")

    tickets = data("tickets.json") or []
    tmap = {}
    seen = set()
    for i, t in enumerate(tickets):
        tb = t.get("body") or {}
        if not verify_sig(authority_pub, str(t.get("sig") or ""), D_TICKET, tb):
            problems.append(f"ticket_signature_invalid:{i}")
            continue
        if tb.get("ticket_id") in seen:
            problems.append(f"ticket_replay:{tb.get('ticket_id')}")
        seen.add(tb.get("ticket_id"))
        tmap[tb.get("ticket_id")] = tb
        if tb.get("mission_id") != m.get("mission_id"):
            problems.append(f"ticket_mission_mismatch:{i}")
    checks.append(f"tickets_verified:{len(tmap)}")

    actions = data("actions.json") or []
    executed = 0
    for i, a in enumerate(actions):
        if a.get("executed") or a.get("decision") == "ALLOW":
            executed += 1
            tid = a.get("ticket_id")
            tb = tmap.get(tid)
            if not tb:
                problems.append(f"action_without_valid_ticket:{i}")
                continue
            if tb.get("task_id") != a.get("task_id") or tb.get("operation") != a.get("tool") or tb.get("params_digest") != a.get("params_digest"):
                problems.append(f"action_ticket_binding_mismatch:{i}")
        if a.get("decision") != "ALLOW" and a.get("executed"):
            problems.append(f"refused_action_executed:{i}")
    checks.append(f"actions_bound:{executed}")
    if state == "COMPLETED" and executed == 0:
        problems.append("completed_without_executed_actions")

    # memory never grants authority
    mem = data("memory.json") or {}
    records = mem.get("records") or mem.get("entries") or []
    if isinstance(records, list):
        for r in records:
            if r.get("grants_authority"):
                problems.append("memory_record_grants_authority")
                break
    checks.append(f"memory_records:{len(records) if isinstance(records, list) else 0}")

    # deliverables exist and carry bytes
    deliverables = [k for k in files if k.startswith("deliverables/")]
    checks.append(f"deliverables:{len(deliverables)}")
    if state == "COMPLETED" and not deliverables:
        problems.append("completed_without_deliverable")

    ok = not problems
    out = {"ok": ok, "schema": SCHEMA, "bundle": b, "mission_id": m.get("mission_id"), "state": state,
           "checks": checks, "problems": problems, "files": len(files), "events": len(events),
           "actions": len(actions), "tickets": len(tickets), "deliverables": len(deliverables),
           "note": "self-generated key proves internal consistency and tamper detection, not a third-party identity"}
    print(json.dumps(out, indent=1))
    return 0 if ok else 1


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