"""Writable runtime, read-only cleanup, and YAML capability operations."""

from __future__ import annotations

import hashlib
import os
import shutil
import subprocess
from pathlib import Path
from typing import TypeAlias

from scripts.nutricoach_v150_live_models import (
    CANDIDATE_DIGEST,
    HERMES_WHEEL,
    PROFILE_WHEEL,
)

Identity: TypeAlias = dict[str, str]
WeeklyContract: TypeAlias = dict[str, str | bool]
_DEPENDENCY_SNAPSHOT_NAMES = frozenset({
    "croniter",
    "croniter-6.0.0.dist-info",
    "python_telegram_bot-22.6.dist-info",
    "telegram",
})


def make_writable(root: Path) -> None:
    """Normalize permissions only inside a successor tree."""
    for path in (root, *root.rglob("*")):
        if path.is_symlink():
            continue
        mode = path.stat(follow_symlinks=False).st_mode
        path.chmod(mode | (0o700 if path.is_dir() else 0o600))


def remove_tree(root: Path) -> None:
    """Remove an owned read-only tree after successor-only normalization."""
    if root.is_dir() and not root.is_symlink():
        make_writable(root)
        shutil.rmtree(root)


def dependency_snapshot_digest(root: Path) -> str:
    """Return the canonical digest of one exact dependency snapshot."""
    names = frozenset(path.name for path in root.iterdir())
    if names != _DEPENDENCY_SNAPSHOT_NAMES:
        raise ValueError("dependency_snapshot_inventory")
    rows: list[str] = []
    for path in sorted(root.rglob("*")):
        if path.is_symlink():
            raise ValueError("dependency_snapshot_symlink")
        if path.is_file():
            relative = path.relative_to(root).as_posix()
            payload = hashlib.sha256(path.read_bytes()).hexdigest()
            rows.append(f"{relative}:{payload}")
    return hashlib.sha256("\n".join(rows).encode()).hexdigest()


def install_dependency_snapshot(site: Path, snapshot: Path) -> None:
    """Install the exact frozen croniter tree into a fresh local site."""
    expected = dependency_snapshot_digest(snapshot)
    for name in sorted(_DEPENDENCY_SNAPSHOT_NAMES):
        source = snapshot / name
        destination = site / name
        if destination.exists() or destination.is_symlink():
            raise ValueError("dependency_destination_exists")
        _ = shutil.copytree(source, destination, copy_function=shutil.copy2)
    installed = dependency_snapshot_digest_from_site(site)
    if installed != expected:
        raise ValueError("dependency_snapshot_copy")


def dependency_snapshot_digest_from_site(site: Path) -> str:
    """Digest only the frozen dependency members in an installed site."""
    rows: list[str] = []
    for name in sorted(_DEPENDENCY_SNAPSHOT_NAMES):
        source = site / name
        if not source.is_dir() or source.is_symlink():
            raise ValueError("dependency_missing")
        for path in sorted(source.rglob("*")):
            if path.is_symlink():
                raise ValueError("dependency_snapshot_symlink")
            if path.is_file():
                relative = path.relative_to(site).as_posix()
                payload = hashlib.sha256(path.read_bytes()).hexdigest()
                rows.append(f"{relative}:{payload}")
    return hashlib.sha256("\n".join(rows).encode()).hexdigest()


def channel_inbox_enabled(payload: str) -> bool:
    """Treat omission as OFF and only explicit/derived true as ON."""
    lines = payload.splitlines()
    truthy = {"1", "on", "true", "yes"}
    for index, line in enumerate(lines):
        stripped = line.split("#", 1)[0].rstrip()
        if not stripped.lstrip().startswith("channel_inbox:"):
            continue
        indent = len(stripped) - len(stripped.lstrip())
        value = stripped.split(":", 1)[1].strip().casefold()
        if value:
            return value in truthy
        for child in lines[index + 1 :]:
            child_text = child.split("#", 1)[0].rstrip()
            if not child_text.strip():
                continue
            child_indent = len(child_text) - len(child_text.lstrip())
            if child_indent <= indent:
                break
            key, separator, flag = child_text.strip().partition(":")
            if separator and key in {"authorized", "configured", "enabled"}:
                if flag.strip().casefold() in truthy:
                    return True
    return False


def enable_weekly_config(
    payload: str,
    candidate_digest: str = CANDIDATE_DIGEST,
) -> bytes:
    """Publish nested weekly operations authority without adding Inbox."""
    lines = payload.splitlines()
    index = next(
        (
            position
            for position, line in enumerate(lines)
            if line.split("#", 1)[0].strip() == "nutrition_coaching:"
        ),
        -1,
    )
    if index < 0:
        suffix = "\nplatforms:\n  telegram:\n    extra:\n      nutrition_coaching:\n"
        payload = payload.rstrip() + suffix
        lines = payload.splitlines()
        index = len(lines) - 1
    indent = len(lines[index]) - len(lines[index].lstrip()) + 2
    prefix = " " * indent
    insert = [
        f"{prefix}weekly_operations:",
        f"{prefix}  enabled: true",
        f"{prefix}weekly_operations_capacity: 5",
        f"{prefix}weekly_operations_authority:",
        f"{prefix}  candidate_digest: {candidate_digest}",
        f"{prefix}  weekly_pilot_authorized: true",
    ]
    lines[index + 1 : index + 1] = insert
    return ("\n".join(lines) + "\n").encode()


def weekly_config_contract(
    payload: str,
    candidate_digest: str = CANDIDATE_DIGEST,
) -> WeeklyContract:
    """Parse the nested weekly postimage used by the readiness fence."""
    required = {
        "enabled: true",
        "weekly_operations_capacity: 5",
        "weekly_weekday: 0",
        f"candidate_digest: {candidate_digest}",
    }
    stripped = {line.strip() for line in payload.splitlines()}
    schedule = (
        {"reminder_time: 20:00:00", "reminder_time: '20:00:00'"},
        {"missed_cutoff_time: 23:00:00", "missed_cutoff_time: '23:00:00'"},
    )
    return {
        "candidate_digest": candidate_digest
        if f"candidate_digest: {candidate_digest}" in stripped
        else "",
        "channel_inbox_present": any(
            line.startswith("channel_inbox:") for line in stripped
        ),
        "enabled": required.issubset(stripped)
        and all(values & stripped for values in schedule),
    }


def run_installed_weekly_startup_smoke(
    runtime: Path,
    profile: Path,
    config: Path,
    *,
    candidate_digest: str = CANDIDATE_DIGEST,
    hermes_wheel: Path = HERMES_WHEEL,
    profile_wheel: Path = PROFILE_WHEEL,
    source_dependencies: bool = False,
) -> None:
    """Run the offline startup fence through the exact installed interpreter."""
    source_root = Path(__file__).resolve().parents[1]
    script = source_root / "scripts/nutricoach_v150_weekly_startup_smoke.py"
    if source_dependencies:
        inherited = tuple(
            entry
            for entry in os.environ.get("PYTHONPATH", "").split(os.pathsep)
            if entry
        )
        pythonpath = (
            *inherited,
            str(source_root),
            str(source_root / "dualcoach/profile"),
        )
    else:
        pythonpath = (str(hermes_wheel), str(profile_wheel), str(source_root))
    environment = {
        "PATH": "/usr/bin:/bin",
        "PYTHONPATH": os.pathsep.join(pythonpath),
    }
    _ = subprocess.run(
        (
            str(runtime / "bin/python"),
            str(script),
            "--profile",
            str(profile),
            "--config",
            str(config),
            "--candidate",
            candidate_digest,
        ),
        check=True,
        capture_output=True,
        env=environment,
    )


def install_fresh_runtime(
    runtime: Path,
    hermes_wheel: Path = HERMES_WHEEL,
    profile_wheel: Path = PROFILE_WHEEL,
    dependency_snapshot: Path | None = None,
) -> Identity:
    """Create a fresh writable venv and install the two exact wheels offline."""
    if runtime.exists() or runtime.is_symlink():
        message = "runtime_exists"
        raise ValueError(message)
    runtime.parent.mkdir(parents=True)
    _ = subprocess.run(
        (
            "/home/cube/miniconda3/bin/python3.12",
            "-m",
            "venv",
            "--system-site-packages",
            str(runtime),
        ),
        check=True,
        capture_output=True,
    )
    _ = subprocess.run(
        (
            "/home/cube/.local/bin/uv",
            "--no-cache",
            "pip",
            "install",
            "--python",
            str(runtime / "bin/python"),
            "--offline",
            "--no-deps",
            "--reinstall",
            str(hermes_wheel),
            str(profile_wheel),
        ),
        check=True,
        capture_output=True,
        env={"PATH": "/usr/bin:/bin", "UV_OFFLINE": "1"},
    )
    site = next((runtime / "lib").glob("python*/site-packages"))
    if dependency_snapshot is not None:
        install_dependency_snapshot(site, dependency_snapshot)
    hermes_record = site / "hermes_agent-0.17.0.dist-info/RECORD"
    profile_record = site / "physique_checkin_cli-0.1.0.dist-info/RECORD"
    imported = subprocess.run(
        (
            str(runtime / "bin/python"),
            "-c",
            "import checkin_cli,croniter,hermes_cli;print(checkin_cli.__file__)",
        ),
        check=True,
        capture_output=True,
        text=True,
    )
    scripts = tuple(
        path.name for path in (runtime / "bin").iterdir() if path.name != "python"
    )
    return {
        "hermes_record": hashlib.sha256(hermes_record.read_bytes()).hexdigest(),
        "hermes_script": ",".join(sorted(scripts)),
        "profile_import": imported.stdout.strip(),
        "profile_record": hashlib.sha256(profile_record.read_bytes()).hexdigest(),
    }
