#!/usr/bin/env python3
"""External v2 binding wrapper for the byte-identical production runtime."""

from __future__ import annotations

import hashlib
import importlib.util
import json
import sys
from pathlib import Path
from types import ModuleType

ROOT = Path(__file__).resolve().parent
SOURCE = Path("/home/cube/projects/richard/hermes-agent")
DIRECT_URL = (
    SOURCE
    / ".venv/lib/python3.12/site-packages/hermes_agent-0.17.0.dist-info/direct_url.json"
)
CANDIDATE = Path(
    "/home/cube/projects/richard/traning coach/.omo/evidence/task26/"
    "task26-test-isolated-successor-e788f5d56aef04da3097007e2ab79614f2060607d4331162169733b1208d9377"
)
SUCCESSOR = "e788f5d56aef04da3097007e2ab79614f2060607d4331162169733b1208d9377"
CORE = "a113a57564a11710dffd238688dd73f8037eabaed0b48532b4bc90b2996e69fc"
WHEEL = "2fbd6c9ad9d4b5ee979e7671d44e32fd4769e8737e26d7459fe73c81a525c656"
RUNTIME = {
    "gateway/platforms/dualcoach_activation_cutover.py": "95637abce4742d583534cf406b038f7c862ad0a72d10a6bab24d2452dcb0f776",
    "gateway/platforms/dualcoach_admin.py": "8c7065277d5d96ce1012ac0c098d53288bba66c44c0674704be4072fe0a63951",
    "gateway/platforms/telegram_customer_bootstrap.py": "8ce2fe8770c2b480083e9d44237d80892ccddcaec06acca14db18576a2ee0088",
    "gateway/platforms/telegram.py": "b41060dea28eb3bbb83217068f5218d5df2c879dba00e73c9ca4e577a6049dad",
}


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


def verify_binding() -> None:
    direct = json.loads(DIRECT_URL.read_text())
    if direct != {"url": f"file://{SOURCE}", "dir_info": {"editable": True}}:
        raise RuntimeError("installed editable runtime binding drift")
    manifest = json.loads((CANDIDATE / "candidate-manifest.json").read_text())
    parity = json.loads(
        (CANDIDATE / "verification/production-invariance.json").read_text()
    )
    if (
        manifest.get("full_candidate_digest") != SUCCESSOR
        or manifest.get("core_candidate_digest") != CORE
        or manifest.get("wheel", {}).get("sha256") != WHEEL
        or parity.get("status") != "PASS"
        or len(parity.get("modules", [])) != 3
        or not all(module.get("matches_30b") is True for module in parity["modules"])
    ):
        raise RuntimeError("candidate binding or 3/3 production parity drift")
    for relative, expected in RUNTIME.items():
        if digest(SOURCE / relative) != expected:
            raise RuntimeError(f"production runtime drift: {relative}")


def load_observer() -> ModuleType:
    spec = importlib.util.spec_from_file_location(
        "task26_continuous_lifecycle_v2", ROOT / "continuous_lifecycle.py"
    )
    if spec is None or spec.loader is None:
        raise RuntimeError("observer import unavailable")
    module = importlib.util.module_from_spec(spec)
    sys.modules[spec.name] = module
    spec.loader.exec_module(module)
    if module.SUCCESSOR != SUCCESSOR or module.CORE != CORE or module.WHEEL != WHEEL:
        raise RuntimeError("observer digest binding drift")
    module.SITE = SOURCE
    return module


def main() -> int:
    try:
        verify_binding()
        return int(load_observer().main())
    except (OSError, ValueError, RuntimeError, KeyError) as exc:
        print(f"FAIL: {exc}", file=sys.stderr)
        return 2


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