#!/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",
)
EXPECTED_SUCCESSOR = "30bcd6633875050aa4f56f49a8bb26cd616ffa2409fc04caef523a8a62d5d1cc"


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 / "continuous_lifecycle.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")
    proof = {
        "schema": "task26-continuous-lifecycle-independent-proof-v1",
        "status": "PASS_INDEPENDENT_ARM_ONLY",
        "authority_unchanged": True,
        "authority_sha256": after,
        "arm_only_sha256": digest(arm),
        "successor": EXPECTED_SUCCESSOR,
        "initial_handoff": document["initial_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())
