#!/usr/bin/env python3
"""Independent no-network arm-only verifier for Task26 observer v5."""

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")
KEY = "task26_live_2e_r2_20260815_8527916639"
SUCCESSOR = "4e9962be49b72951c3b9ed7e1a4fe36d0ca03e757872ae03364c1ab7a790f32b"
EXPECTED_CALLBACK = "non2:owner_ok:29:U7T5W1tNuaYREol2p7lRu-ItlhngWy_wf631sC-aU4A"
AUTHORITIES = (
    PROFILE / "customers/registry.json",
    PROFILE / "data/onboarding/telegram-customer-bootstrap-v1/ledger.json",
    PROFILE / f"data/customers/{KEY}/nutrition-onboarding/transient/workflow.json",
    PROFILE / f"data/customers/{KEY}/nutrition-onboarding/baseline-candidate.json",
    PROFILE / f"data/customers/{KEY}/nutrition-onboarding/session.json",
    PROFILE / "data/onboarding/telegram-publication-outbox-v1/ledger.json",
    PROFILE / "data/onboarding/telegram-publication-outbox-v1/owner-callbacks.json",
)


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


def exclusive_json(path: Path, document: object) -> None:
    with path.open("x") as stream:
        json.dump(document, stream, sort_keys=True, separators=(",", ":"))
        stream.write("\n")
        stream.flush()
    path.chmod(0o600)


def main() -> int:
    before = {str(path): digest(path) for path in AUTHORITIES}
    ready = ROOT / "independent-arm-only-v2.json"
    result = subprocess.run(
        [
            sys.executable,
            str(ROOT / "observer_v5.py"),
            "arm-only",
            "--profile",
            str(PROFILE),
            "--ready",
            str(ready),
        ],
        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")
    handoff = document.get("initial_handoff", {})
    if (
        document.get("status") != "READY_CONTINUOUS_LIFECYCLE"
        or document.get("bindings", {}).get("successor") != SUCCESSOR
        or document.get("baseline_validation") != "PASS_OWNER_BASELINE"
        or handoff.get("status") != "READY_OWNER_REVIEW"
        or handoff.get("role") != "owner"
        or handoff.get("actor") != "8693203710"
        or handoff.get("route") != ["8693203710", "0"]
        or handoff.get("message_id") != "215"
        or handoff.get("action") != EXPECTED_CALLBACK
    ):
        raise RuntimeError("current generation-29 owner handoff drift")
    proof = {
        "schema": "task26-observer-v5-independent-proof-v1",
        "status": "PASS_INDEPENDENT_NO_NETWORK_ARM_ONLY",
        "authority_unchanged": True,
        "authority_sha256": after,
        "arm_only_sha256": digest(ready),
        "successor": SUCCESSOR,
        "baseline_validation": "PASS_OWNER_BASELINE",
        "current_handoff": handoff,
        "network_calls": 0,
        "profile_mutations": 0,
        "service_actions": 0,
        "ui_actions": 0,
    }
    exclusive_json(ROOT / "independent-proof-v2.json", proof)
    print(json.dumps(proof, sort_keys=True))
    return 0


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