#!/usr/bin/env python3
"""Independent arm-only verification; never writes profile authority."""

from __future__ import annotations

import hashlib
import json
import subprocess
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent
PROFILE = Path("/home/cube/.hermes/profiles/dualcoachtest")
AUTHORITIES = (
    PROFILE / "customers/registry.json",
    PROFILE / "data/onboarding/telegram-customer-bootstrap-v1/ledger.json",
    PROFILE
    / "data/customers/task26_live_2e_r2_20260815_8527916639/nutrition-onboarding/transient/workflow.json",
    PROFILE / "data/onboarding/telegram-publication-outbox-v1/ledger.json",
    PROFILE
    / "data/customers/task26_live_2e_r2_20260815_8527916639/nutrition-onboarding/session.json",
    PROFILE / "data/telegram-ingress-receipts-v1-d0aacf0f4bdbb7c0.json",
)
EXPECTED_SUCCESSOR = "e788f5d56aef04da3097007e2ab79614f2060607d4331162169733b1208d9377"


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


def main() -> int:
    before = {str(path): digest(path) for path in AUTHORITIES}
    arm = ROOT / "independent-arm-only.json"
    if arm.exists():
        raise RuntimeError(f"refusing to replace append-only proof: {arm}")
    result = subprocess.run(
        [
            sys.executable,
            str(ROOT / "observer_v2.py"),
            "arm-only",
            "--profile",
            str(PROFILE),
            "--ready",
            str(arm),
        ],
        check=True,
        capture_output=True,
        text=True,
    )
    document = json.loads(result.stdout)
    after = {str(path): digest(path) for path in AUTHORITIES}
    if before != after:
        raise RuntimeError("live authority changed during arm-only verification")
    if document.get("status") != "READY_CONTINUOUS_LIFECYCLE":
        raise RuntimeError("arm-only did not return readiness")
    if document.get("bindings", {}).get("successor") != EXPECTED_SUCCESSOR:
        raise RuntimeError("successor binding mismatch")
    handoff = document.get("initial_handoff", {})
    if (
        handoff.get("status") != "READY_CUSTOMER_ONBOARDING"
        or handoff.get("message_id") != "161"
        or handoff.get("action") != "submit_answer:date_of_birth"
    ):
        raise RuntimeError("live initial handoff drift")
    proof = {
        "schema": "task26-continuous-lifecycle-independent-proof-v2",
        "status": "PASS_INDEPENDENT_ARM_ONLY",
        "authority_unchanged": True,
        "authority_sha256": after,
        "arm_only_sha256": digest(arm),
        "successor": EXPECTED_SUCCESSOR,
        "initial_handoff": handoff,
    }
    target = ROOT / "independent-proof.json"
    fd = target.open("x")
    try:
        json.dump(proof, fd, sort_keys=True, separators=(",", ":"))
        fd.write("\n")
        fd.flush()
    finally:
        fd.close()
    target.chmod(0o600)
    print(json.dumps(proof, sort_keys=True))
    return 0


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