"""Detached stdlib-only controller-closure bootstrap."""

from __future__ import annotations

import argparse
import hashlib
import json
import os
import re
import stat
import sys
from pathlib import Path
from typing import cast

PRESEAL = Path(
    "/home/cube/.hermes/migrations/nutricoach-v1.5.0-combined/"
    + "live-transaction-preseal-v15-runtime-authority-r71b-maintenance"
)


class BootstrapDenied(RuntimeError):
    """Detached bootstrap integrity denial."""


def _document(path: Path) -> dict[str, str]:
    text = path.read_text(encoding="utf-8")
    marker = re.search(r'"(?:entries|files)"\s*:\s*\{', text)
    if marker is None:
        raise BootstrapDenied("document")
    end = text.find("}", marker.end())
    if end < 0:
        raise BootstrapDenied("document")
    pairs = re.findall(r'"([^"]+)"\s*:\s*"([0-9a-f]{64})"', text[marker.end() : end])
    if not pairs:
        raise BootstrapDenied("rows")
    return dict(pairs)


def verify_package_inventory(manifest: Path, root: Path) -> None:
    """Verify every self-excluding preseal package entry."""
    rows = _document(manifest)
    actual = {
        path.relative_to(root).as_posix()
        for path in root.rglob("*")
        if path.is_file() and not path.is_symlink()
    }
    if actual != set(rows) | {manifest.relative_to(root).as_posix()}:
        raise BootstrapDenied("package_inventory")
    for relative, expected in sorted(rows.items()):
        path = root / relative
        if (
            not path.is_file()
            or path.is_symlink()
            or stat.S_IMODE(path.stat(follow_symlinks=False).st_mode) & 0o222
            or hashlib.sha256(path.read_bytes()).hexdigest() != expected
        ):
            raise BootstrapDenied("package_drift")


def verify_closure(
    manifest: Path,
    root: Path,
    *,
    exact_inventory: bool = True,
) -> str:
    """Verify the complete controller closure before importing it."""
    rows = _document(manifest)
    actual = {
        path.relative_to(root).as_posix()
        for path in root.rglob("*")
        if path.is_file() and not path.is_symlink()
    }
    if exact_inventory and actual != set(rows):
        raise BootstrapDenied("closure_inventory")
    canonical: list[str] = []
    for relative, expected in sorted(rows.items()):
        path = root / relative
        if not path.resolve().is_relative_to(root.resolve()) or not path.is_file():
            raise BootstrapDenied("closure_path")
        actual = hashlib.sha256(path.read_bytes()).hexdigest()
        if actual != expected:
            raise BootstrapDenied("closure_drift")
        canonical.append(f"{relative}:{actual}")
    payload = "\n".join(canonical).encode()
    return "sha256:" + hashlib.sha256(payload).hexdigest()


def verify_network_isolation(proc_net: Path | None = None) -> None:
    """Deny any namespace exposing a non-loopback interface or route."""
    root = proc_net or Path("/proc/net")
    try:
        interfaces = {
            line.split(":", 1)[0].strip()
            for line in (root / "dev").read_text(encoding="utf-8").splitlines()
            if ":" in line
        }
        routes = [
            line.split()
            for line in (root / "route").read_text(encoding="utf-8").splitlines()[1:]
            if line.strip()
        ]
    except OSError as exc:
        raise BootstrapDenied("network_namespace") from exc
    if interfaces != {"lo"} or any(route[0] != "lo" for route in routes):
        raise BootstrapDenied("network_namespace")


def verified_pythonpath(target: Path, source_root: Path) -> str:
    """Return exact sealed wheels before controller source on the import path."""
    try:
        loaded = cast(object, json.loads(target.read_text(encoding="utf-8")))
    except (OSError, ValueError, AttributeError) as error:
        raise BootstrapDenied("wheel_manifest") from error
    if not isinstance(loaded, dict):
        raise BootstrapDenied("wheel_manifest")
    document = cast(dict[str, object], loaded)
    wheels = document.get("wheels")
    if not isinstance(wheels, list):
        raise BootstrapDenied("wheel_manifest")
    wheel_rows = cast(list[object], wheels)
    if len(wheel_rows) != 2:
        raise BootstrapDenied("wheel_manifest")
    paths: list[str] = []
    for item in wheel_rows:
        if not isinstance(item, dict):
            raise BootstrapDenied("wheel_manifest")
        row = cast(dict[str, object], item)
        raw_path = row.get("path")
        expected = row.get("sha256")
        if not isinstance(raw_path, str) or not isinstance(expected, str):
            raise BootstrapDenied("wheel_manifest")
        path = Path(raw_path)
        try:
            info = path.stat(follow_symlinks=False)
            actual = hashlib.sha256(path.read_bytes()).hexdigest()
        except OSError as error:
            raise BootstrapDenied("wheel_integrity") from error
        if (
            path.is_symlink()
            or not stat.S_ISREG(info.st_mode)
            or info.st_uid != os.geteuid()
            or info.st_nlink != 1
            or stat.S_IMODE(info.st_mode) & 0o222
            or actual != expected
        ):
            raise BootstrapDenied("wheel_integrity")
        paths.append(str(path))
    paths.append(str(source_root))
    return os.pathsep.join(paths)


class BootstrapNamespace(argparse.Namespace):
    """Typed detached bootstrap arguments."""

    def __init__(self) -> None:
        super().__init__()
        self.approval: str = ""


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    _ = parser.add_argument("--approval", required=True)
    args = parser.parse_args(namespace=BootstrapNamespace())
    approval = args.approval
    verify_network_isolation()
    source_root = PRESEAL / "controller-source"
    _ = verify_closure(PRESEAL / "controller-source-manifest.json", source_root)
    verify_package_inventory(PRESEAL / "package-manifest.json", PRESEAL)
    environment = dict(os.environ)
    environment["PYTHONDONTWRITEBYTECODE"] = "1"
    environment["PYTHONPATH"] = verified_pythonpath(
        PRESEAL / "sealed-target.json", source_root
    )
    worker = source_root / "scripts/nutricoach_v150_controller_worker.py"
    os.execve(
        sys.executable,
        (
            sys.executable,
            "-B",
            str(worker),
            "--approval",
            approval,
        ),
        environment,
    )


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