#!/usr/bin/env python3
"""Independent verifier for the sealed Task26 post-claim live receipt."""
from __future__ import annotations

import argparse
import hashlib
import json
import os
from pathlib import Path
from typing import Any

HERE = Path(__file__).resolve().parent
EXPECTED = {
    "post_claim_adjudicator.py": "4e673a965c56a1e7d6f2a9e067147cec967594987f5b38051ca1096365f0ec25",
    "test_post_claim_adjudicator.py": "698c25663392805436218377adb39ef73c5f9333a413832bb24bb35317217ff7",
    "schema.json": "0a91aba75ac4e2d65e5230e474d9ef123982a4608034a3a1fc032ead28f7252f",
}
SESSION = "cb_PCczfFXoI4GjvCxLBs1oRA"
ACTOR = "8527916639"
CURRENT_DIGEST = "a9b73fcd6f46884857c14fdb94db0618f306225e9c17ed36b9a5b3a343bcdd48"


def canonical(value: Any) -> bytes:
    return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()


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


def write_once(path: Path, value: dict[str, Any]) -> None:
    path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_CLOEXEC, 0o600)
    try:
        os.write(fd, canonical(value) + b"\n")
        os.fsync(fd)
    finally:
        os.close(fd)


def verify(profile: Path, live_receipt: Path) -> dict[str, Any]:
    for name, wanted in EXPECTED.items():
        if sha(HERE / name) != wanted:
            raise RuntimeError(f"sealed artifact mismatch: {name}")
    permission = json.loads((HERE / "permission-seal.json").read_text())
    if any(permission.get(key) != value for key, value in {
        "harness_sha256": EXPECTED["post_claim_adjudicator.py"],
        "test_sha256": EXPECTED["test_post_claim_adjudicator.py"],
        "schema_sha256": EXPECTED["schema.json"],
    }.items()):
        raise RuntimeError("permission seal mismatch")
    ledger = json.loads((profile / "data/onboarding/telegram-customer-bootstrap-v1/ledger.json").read_text())
    payload = {"schema": ledger["schema"], "sessions": ledger["sessions"]}
    if ledger.get("digest") != hashlib.sha256(canonical(payload)).hexdigest() or ledger.get("digest") != CURRENT_DIGEST:
        raise RuntimeError("live ledger digest mismatch")
    sessions = ledger.get("sessions")
    if not isinstance(sessions, list) or len(sessions) != 2:
        raise RuntimeError("live session cardinality mismatch")
    old, current = sessions
    claim = {"role": "customer", "user_id": ACTOR, "chat_id": ACTOR,
             "topic_id": "0", "message_id": "158"}
    positive = bool(
        old.get("state") == "EXPIRED"
        and old.get("session_id") == "cb_v4olwxbpSQatMtVLR4QLmw"
        and current.get("session_id") == SESSION
        and current.get("state") == "AWAITING_CONSENT"
        and current.get("generation") == 4
        and current.get("recovery_attempt_generation") == 1
        and current.get("role_claims") == [claim]
        and current.get("consent_publication_attempt") == 1
        and current.get("consent_card_message_id") == "159"
    )
    if not positive:
        raise RuntimeError("successful claim positive evidence mismatch")
    registry = json.loads((profile / "customers/registry.json").read_text())
    rows = registry.get("customers")
    if not isinstance(rows, list):
        raise RuntimeError("registry row count UNKNOWN")
    receipt = json.loads(live_receipt.read_text())
    if len(rows) != 1:
        raise RuntimeError("expected live normal-path disabled registry row is absent")
    row = rows[0]
    telegram = row.get("telegram") if isinstance(row, dict) else None
    if not isinstance(telegram, dict) or row.get("enabled") is not False or telegram != {
        "user_id": ACTOR, "chat_id": ACTOR, "topic_id": "0"
    }:
        raise RuntimeError("normal-path disabled registry row mismatch")
    if receipt.get("status") != "FAIL" or receipt.get("blocker") != "required no customer registry row, observed 1 row(s)":
        raise RuntimeError("live adjudicator did not fail closed on contradictory predicate")
    return {
        "schema": "task26-post-claim-independent-verification-v1",
        "status": "PASS_VERIFIED_FAIL_CLOSED",
        "successful_claim_positive_evidence": True,
        "requested_no_registry_row": False,
        "observed_disabled_registry_rows": 1,
        "live_pass_successful_claim_issued": False,
        "reason": "candidate normal path creates the disabled registry row before AWAITING_CONSENT",
        "check_count": 16,
    }


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--profile", type=Path, required=True)
    parser.add_argument("--live-receipt", type=Path, required=True)
    parser.add_argument("--receipt", type=Path, required=True)
    args = parser.parse_args()
    try:
        result = verify(args.profile, args.live_receipt)
        code = 0
    except (OSError, ValueError, KeyError, TypeError, RuntimeError, json.JSONDecodeError) as exc:
        result = {"schema": "task26-post-claim-independent-verification-v1",
                  "status": "FAIL", "blocker": str(exc), "unknown_is_failure": True}
        code = 2
    write_once(args.receipt, result)
    print(json.dumps({"status": result["status"], "receipt": str(args.receipt)}, sort_keys=True))
    return code


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