#!/usr/bin/env python3
"""Independent no-network, arm-only verification for observer v3."""

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"
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/session.json",
    PROFILE / "data/onboarding/telegram-publication-outbox-v1/ledger.json",
    PROFILE / "data/onboarding/telegram-publication-outbox-v1/owner-callbacks.json",
)
SUCCESSOR = "e2f1699e8586ed3f835eaa2a3eaeaecaf5e52a4ad82aa931caade0ed377077ce"


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"
    if ready.exists():
        raise RuntimeError(f"refusing to replace append-only proof: {ready}")
    result = subprocess.run(
        [
            sys.executable,
            str(ROOT / "observer_v3.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")
    if document.get("status") != "READY_CONTINUOUS_LIFECYCLE":
        raise RuntimeError("observer did not arm")
    if document.get("bindings", {}).get("successor") != SUCCESSOR:
        raise RuntimeError("successor binding mismatch")
    handoff = document.get("initial_handoff", {})
    revision = document.get("candidate_summary_revision", {})
    if (
        handoff.get("status") != "STOP_CUSTOMER_SUMMARY_QUALITY"
        or handoff.get("message_id") != "207"
        or revision.get("status") != "READY_CUSTOMER_SUMMARY_REVISION"
        or revision.get("message_id") != "207"
        or revision.get("next_field") != "schedule_constraints"
        or revision.get("next_value") != "없음"
    ):
        raise RuntimeError("live summary/revision classification drift")
    proof = {
        "schema": "task26-continuous-lifecycle-independent-proof-v3",
        "status": "PASS_ARM_ONLY_BLOCKER_DETECTED",
        "authority_unchanged": True,
        "authority_sha256": after,
        "arm_only_sha256": digest(ready),
        "successor": SUCCESSOR,
        "initial_handoff": handoff,
        "candidate_summary_revision": revision,
        "network_calls": 0,
        "profile_mutations": 0,
    }
    exclusive_json(ROOT / "independent-proof-v2.json", proof)
    print(json.dumps(proof, sort_keys=True))
    return 0


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