#!/usr/bin/env python3
"""Independent static and live arm-only verification for the consent observer."""

from __future__ import annotations

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

HERE = Path(__file__).resolve().parent
HARNESS = HERE / "consent_observer.py"
PROFILE = Path("/home/cube/.hermes/profiles/dualcoachtest")
ARM_RECEIPT = HERE / "live-arm-only.redacted.json"
VERIFY_RECEIPT = HERE / "independent-verification.redacted.json"
TARGETS = (
    PROFILE / "customers/registry.json",
    PROFILE / "data/onboarding/telegram-customer-bootstrap-v1/ledger.json",
)


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


def write_private(path: Path, value: object) -> None:
    descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
    try:
        os.write(descriptor, json.dumps(value, sort_keys=True, separators=(",", ":")).encode() + b"\n")
        os.fsync(descriptor)
    finally:
        os.close(descriptor)


def main() -> int:
    source = HARNESS.read_text()
    tree = ast.parse(source)
    imports = {
        alias.name.split(".", 1)[0]
        for node in ast.walk(tree)
        if isinstance(node, ast.Import)
        for alias in node.names
    } | {
        (node.module or "").split(".", 1)[0]
        for node in ast.walk(tree)
        if isinstance(node, ast.ImportFrom)
    }
    forbidden = imports & {"socket", "requests", "urllib", "httpx", "telegram", "subprocess"}
    calls = {
        f"{getattr(node.func.value, 'id', '')}.{node.func.attr}"
        for node in ast.walk(tree)
        if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
    }
    checks = {
        "no_network_or_provider_import": not forbidden,
        "no_sleep": "time.sleep" not in calls,
        "event_wait": "selectors.DefaultSelector" in source and "inotify_add_watch" in source,
        "bounded_30_minutes": "timeout > 1800" in source,
        "exact_ready_status": "READY_BEFORE_CONSENT" in source,
        "exact_session": "cb_PCczfFXoI4GjvCxLBs1oRA" in source,
        "exact_card": 'CARD_MESSAGE_ID: Final = "159"' in source,
        "exact_actor": 'ACTOR_ID: Final = "8527916639"' in source,
        "current_plan": "d816dbbd6a27d5826b251d279a9831de096ef7cd79b5fd131ceff7253b7369be" in source,
        "runbook_v6": "8416cd7c83cab5540af2e1e01dbcc5b1bdfd49a59d8ef21ea49512c28d749218" in source,
    }
    before = {str(path): digest(path) for path in TARGETS}
    result = subprocess.run(
        [sys.executable, "-B", str(HARNESS), "arm-only", "--profile", str(PROFILE),
         "--receipt", str(ARM_RECEIPT)],
        text=True, capture_output=True, timeout=10, check=False,
    )
    after = {str(path): digest(path) for path in TARGETS}
    arm = json.loads(ARM_RECEIPT.read_text()) if ARM_RECEIPT.exists() else {}
    checks.update({
        "live_arm_exit_zero": result.returncode == 0,
        "live_ready_before_consent": arm.get("status") == "READY_BEFORE_CONSENT",
        "event_subscription_before_action": arm.get("event_subscription") == "inotify-established-before-human-callback",
        "authority_unchanged": before == after,
    })
    receipt = {
        "schema": "task26-consent-observer-independent-verification-v1",
        "status": "PASS" if all(checks.values()) else "FAIL",
        "checks": checks,
        "authority_sha256_before": before,
        "authority_sha256_after": after,
        "harness_sha256": digest(HARNESS),
        "arm_receipt_sha256": digest(ARM_RECEIPT) if ARM_RECEIPT.exists() else None,
        "stderr": result.stderr,
    }
    write_private(VERIFY_RECEIPT, receipt)
    print(json.dumps(receipt, sort_keys=True, separators=(",", ":")))
    return 0 if receipt["status"] == "PASS" else 1


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