#!/usr/bin/env python3
"""Candidate-bound entry point for the Task26 reconciliation observer v3."""

from __future__ import annotations

import hashlib
import importlib.util
import json
import subprocess
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-summary-production-successor-"
    "e2f1699e8586ed3f835eaa2a3eaeaecaf5e52a4ad82aa931caade0ed377077ce"
)
SUCCESSOR = "e2f1699e8586ed3f835eaa2a3eaeaecaf5e52a4ad82aa931caade0ed377077ce"
CORE = "b025a71695b620555f701f1c248545bd343428c430db37b2d8bd16148e0b0b7a"
WHEEL = "bd5f44592e95b152cc466446fcbb607df586dc13482d0d3413fed80a476d2a70"
SOURCE_PARITY = {
    "gateway/platforms/nutrition_onboarding_reconciliation.py": "8fb6ba6f855e7508c525447cdec482ceb240f8c0a5827b2ca0ce4268c6880bb0",
    "gateway/platforms/telegram_nutrition_onboarding_runtime.py": "d6a7b3c7550c40f7290d7c56e7561885325f347e967cb676812161c2e5efb10d",
    "gateway/platforms/telegram_nutrition_onboarding_runtime_callback.py": "bf2f312245b59ebf33dd1e3e449cfffed12809d18f820953cc28cecef25d34d2",
    "gateway/platforms/telegram_nutrition_onboarding_runtime_publication.py": "f04ea498ad12a257fb1322da4c8cfd2f91fc9403f0b978617fcc00df41729209",
}
PROFILE_SOURCE_PARITY = {
    "nutrition_onboarding.py": "d1f848d1fa8bc71e018f45c83e8e19e93671dfa83157d3feff15b8f7ec0f1d8a",
    "nutrition_onboarding_contract.py": "327267e12c2e6250218652811cca403a80c1704753f2caace7d8b1e446d21417",
}
PROFILE_PACKAGE = Path(
    "/home/cube/.hermes/profiles/dualcoachtest/workspace/checkin_cli/checkin_cli"
)


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")
    result = subprocess.run(
        [sys.executable, str(CANDIDATE / "verify_candidate.py"), str(CANDIDATE)],
        check=True,
        capture_output=True,
        text=True,
    )
    verification = json.loads(result.stdout)
    manifest = json.loads((CANDIDATE / "candidate-manifest.json").read_text())
    if (
        verification.get("status") != "PASS"
        or verification.get("full") != SUCCESSOR
        or verification.get("core") != CORE
        or verification.get("wheel") != WHEEL
        or manifest.get("readiness") != "READY_FOR_GATE18_20_RECERTIFICATION"
    ):
        raise RuntimeError("candidate verifier or digest binding drift")
    wheel = CANDIDATE / "artifacts/hermes_agent-0.17.0-py3-none-any.whl"
    if digest(wheel) != WHEEL:
        raise RuntimeError("candidate wheel drift")
    for relative, expected in SOURCE_PARITY.items():
        if digest(SOURCE / relative) != expected:
            raise RuntimeError(f"candidate source parity drift: {relative}")
    for relative, expected in PROFILE_SOURCE_PARITY.items():
        if digest(PROFILE_PACKAGE / relative) != expected:
            raise RuntimeError(f"profile onboarding source drift: {relative}")


def load_observer() -> ModuleType:
    spec = importlib.util.spec_from_file_location(
        "task26_continuous_lifecycle_v3", 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")
    setattr(module, "SITE", SOURCE)
    return module


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


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