#!/usr/bin/env python3
"""Plan memory across local runtimes; never load or scan the Bible corpus.

Cache settings are entry counts, not measured byte budgets. The cgroup and
systemd ceilings enforce memory; this planner conservatively chooses worker,
concurrency and public librarian cache settings inside those ceilings.
"""
from __future__ import annotations

import argparse
from decimal import Decimal
import hashlib
import json
import math
import os
from pathlib import Path
import re
import subprocess
import sys
import time

MIB = 1024 ** 2
MINIMUM = {"query": 192 * MIB, "search": 512 * MIB}
WEIGHT = {"query": 1, "search": 4}
MCP_MEMORY_MAX = 256 * MIB


def memory_bytes(value: str) -> int:
    match = re.fullmatch(r"\s*(\d+(?:\.\d+)?)\s*([kmgt]?)(?:i?b)?\s*", value.lower())
    if not match:
        raise ValueError(f"Invalid memory size {value!r}; use bytes or K/M/G/T, for example 4G.")
    amount = int(Decimal(match[1]) * (1024 ** ("kmgt".index(match[2]) + 1) if match[2] else 1))
    if amount <= 0:
        raise ValueError("Memory budget must be greater than zero.")
    return amount


def config(path: Path) -> dict[str, str]:
    if not path.is_file():
        return {}
    return dict(line.split("=", 1) for line in path.read_text().splitlines()
                if re.match(r"^[A-Z][A-Z0-9_]*=", line))


def host_memory(proc: Path) -> int | None:
    """Physical RAM is an upper bound, never a container's missing budget."""
    try:
        for line in (proc / "meminfo").read_text().splitlines():
            match = re.fullmatch(r"MemTotal:\s+(\d+)\s+kB", line)
            if match:
                return int(match[1]) * 1024
    except FileNotFoundError:
        pass
    return None


def available_memory(proc: Path) -> int | None:
    try:
        for line in (proc / "meminfo").read_text().splitlines():
            match = re.fullmatch(r"MemAvailable:\s+(\d+)\s+kB", line)
            if match:
                return int(match[1]) * 1024
    except FileNotFoundError:
        pass
    return None


def cgroup_limits(proc: Path, override: Path | None = None, owner: str = "self") -> dict:
    """Read this process's cgroup and every ancestor visible in its namespace.

    Mount roots can differ from membership paths (a subtree mount); never
    substitute host MemTotal for the container's actual memory.max.
    """
    affinity_pid = 0 if owner == "self" else int(owner)
    cpus = float(len(os.sched_getaffinity(affinity_pid))) if hasattr(os, "sched_getaffinity") else float(os.cpu_count() or 1)
    result = {"memory": None, "memory_path": None, "cpus": cpus}
    membership = proc / owner / "cgroup"
    if not membership.is_file():
        if owner != "self":
            raise ValueError("Cannot inspect PID 1 cgroup membership for the aggregate runtime budget.")
        return result
    member = next((line[3:] for line in membership.read_text().splitlines() if line.startswith("0::")), None)
    if member is None:
        return result
    mounts = []
    mountinfo = proc / "self/mountinfo"
    if mountinfo.is_file():
        for line in mountinfo.read_text().splitlines():
            before, sep, after = line.partition(" - ")
            if not sep or after.split()[0] != "cgroup2":
                continue
            fields = before.split()
            unescape = lambda text: re.sub(r"\\([0-7]{3})", lambda m: chr(int(m[1], 8)), text)
            root, target = Path(unescape(fields[3])), Path(unescape(fields[4]))
            if Path(member).is_relative_to(root):
                mounts.append((root, target))
    if not mounts:
        if override is None:
            return result
        mounts = [(Path("/"), override)]
    root, target = max(mounts, key=lambda item: len(item[0].parts))
    if override is not None:
        target = override
    current = target / Path(member).relative_to(root)
    if not current.is_dir():
        return result
    while True:
        maximum = current / "memory.max"
        if maximum.is_file():
            raw = maximum.read_text().strip()
            if raw != "max":
                value = int(raw)
                if result["memory"] is None or value < result["memory"]:
                    result.update(memory=value, memory_path=str(maximum))
        cpu = current / "cpu.max"
        if cpu.is_file():
            quota, period = cpu.read_text().split()
            if quota != "max":
                result["cpus"] = min(result["cpus"], int(quota) / int(period))
        if current == target:
            break
        current = current.parent
    return result


def inventory(registry: Path, runtime: Path) -> list[dict]:
    entries = []
    for domain_file in sorted(registry.glob("*/endpoint.conf")):
        domain = config(domain_file)
        if domain.get("TYPE") != "runtime" or domain.get("ENABLED", "true") != "true":
            continue
        kind = domain.get("KIND", "")
        if kind not in MINIMUM:
            raise ValueError(f"No memory sizing policy is declared for runtime kind {kind!r}.")
        for version_file in sorted((domain_file.parent / "versions").glob("*.conf")):
            version = config(version_file)
            if version.get("ENABLED", "true") != "true":
                continue
            label = version_file.stem
            entries.append({"domain": domain_file.parent.name, "label": label, "kind": kind,
                            "config": version, "root": str(runtime / kind / label)})
    return entries


def mcp_memory(args) -> tuple[int, int, list[dict]]:
    """Separate planned MCP capacity from the generations needed right now."""
    reserve, candidate, live = 0, 0, []
    for path in sorted(Path(args.registry).glob("*/endpoint.conf")):
        settings = config(path)
        enabled = settings.get("TYPE") == "mcp" and settings.get("ENABLED", "true") == "true"
        units = set()
        if not args.offline:
            # The manager records these bounded unit names alongside its
            # immutable generation. No environment file or token is read.
            root = Path(args.runtime_root) / "mcp" / re.sub(r"[^a-z0-9]", "_", path.parent.name)
            for unit_path in root.glob("deployments/*/.unit"):
                unit = unit_path.read_text().strip()
                if not re.fullmatch(r"getbible-mcp-[a-zA-Z0-9-]+", unit):
                    raise ValueError("Invalid saved MCP unit name")
                units.add(unit + ".service")
        running, generations = unit_memory(units, args.systemctl, args.offline)
        live.extend(generations)
        # Keep room for serving+candidate even before first deployment; a
        # slow drain or interrupted prior switch adds its actual process cap.
        reserve += max(2 * MCP_MEMORY_MAX if enabled else 0,
                       running + (MCP_MEMORY_MAX if enabled else 0))
        if enabled and path.parent.name == getattr(args, "candidate_domain", None):
            candidate = MCP_MEMORY_MAX
    return reserve, candidate, live


def allocated(entries: list[dict], extra: int) -> tuple[list[int], int]:
    sizes = [min(item.get("maximum", 2**63), item.get("minimum", MINIMUM[item["kind"]]) + extra * item.get("weight", WEIGHT[item["kind"]])) for item in entries]
    domains: dict[str, int] = {}
    for item, size in zip(entries, sizes):
        domains[item["domain"]] = domains.get(item["domain"], 0) + size
    return sizes, max(domains.values(), default=0)


def selected_ceiling(item: dict) -> int:
    limits = Path(item["root"]) / "active/limits.conf"
    if not limits.is_file():
        return 0
    raw = next((line.split("=", 1)[1] for line in limits.read_text().splitlines()
                if line.startswith("MemoryMax=")), "")
    return memory_bytes(raw) if raw and raw != "infinity" else 0


def domain_changes(result: dict, decreases_only: bool = False, exclude: str = "") -> list[str]:
    """Apply decreases first so adding endpoints cannot strand update capacity."""
    domains: dict[str, list[int]] = {}
    for item in result["endpoints"]:
        totals = domains.setdefault(item["domain"], [0, 0])
        totals[0] += item["selected_memory_max_bytes"]
        totals[1] += item["settings"]["MEMORY_MAX"]
    changed = [(domain, old - new) for domain, (old, new) in domains.items()
               if domain != exclude and old and (old > new if decreases_only else old != new)]
    return [domain for domain, _ in sorted(changed, key=lambda item: (-item[1], item[0]))]


def policy_values(args) -> dict:
    policy = {
        "MEMORY_CACHE_TTL": "2592000", "CACHE_TTL_JITTER": "0",
        "QUERY_CPU_QUOTA": "auto", "SEARCH_CPU_QUOTA": "auto",
        "CACHE_MEMORY_PERCENT": "50", "SHARED_CORPUS_LIMIT": "256",
        "CHAPTER_CACHE_LIMIT": "100000", "TRANSLATION_CACHE_LIMIT": "256",
        "REFERENCE_CACHE_LIMIT": "50000", "RESOURCE_RESERVE_PERCENT": "25",
        "QUERY_MEMORY_MIN": "192M", "SEARCH_MEMORY_MIN": "512M",
        "QUERY_MEMORY_MAX": "auto", "SEARCH_MEMORY_MAX": "auto",
    }
    for kind in ("QUERY", "SEARCH"):
        policy.update({f"{kind}_WORKERS_MIN": "1", f"{kind}_WORKERS_MAX": "12",
                       f"{kind}_THREADS_MIN": "1", f"{kind}_THREADS_MAX": "16" if kind == "QUERY" else "8",
                       f"{kind}_WARM_TRANSLATIONS": "kjv"})
    for argument in getattr(args, "policy", []) or []:
        key, separator, value = argument.partition("=")
        if not separator or key not in policy:
            raise ValueError(f"Unknown resource policy: {key}")
        policy[key] = value
    policy["_authoritative"] = set(getattr(args, "authoritative", []) or [])
    return policy


def bounded(value, name, minimum, maximum):
    try:
        number = int(value)
    except (TypeError, ValueError) as error:
        raise ValueError(f"{name} must be an integer.") from error
    if not minimum <= number <= maximum:
        raise ValueError(f"{name} must be between {minimum} and {maximum}.")
    return number


def endpoint_settings(item: dict, size: int, cpus: float, policy: dict | None = None, mode="docker") -> dict:
    policy = policy or policy_values(argparse.Namespace())
    kind, saved = item["kind"], item["config"]
    prefix = kind.upper()
    def value(key, fallback=None):
        global_key = f"{prefix}_{key}" if f"{prefix}_{key}" in policy else key
        if global_key in policy.get("_authoritative", set()):
            return policy[global_key]
        return saved.get(key, policy.get(global_key, fallback))
    worker_min = bounded(value("WORKERS_MIN"), "WORKERS_MIN", 1, 64)
    worker_max = bounded(value("WORKERS_MAX"), "WORKERS_MAX", worker_min, 64)
    thread_min = bounded(value("THREADS_MIN"), "THREADS_MIN", 1, 64)
    thread_max = bounded(value("THREADS_MAX"), "THREADS_MAX", thread_min, 64)
    quota = value("CPU_QUOTA", "auto")
    if quota == "auto":
        quota = "" if mode == "docker" else ("200%" if kind == "query" else "400%")
    if quota:
        if not re.fullmatch(r"[0-9]+(?:\.[0-9]+)?%", quota) or float(quota[:-1]) <= 0:
            raise ValueError("CPU_QUOTA must be auto or a positive percentage.")
        cpus = min(cpus, float(quota[:-1]) / 100)
    requested_workers = saved.get("WORKERS") or "auto"
    automatic = requested_workers == "auto"
    desired = min(worker_max, max(worker_min, math.ceil(cpus))) if automatic else bounded(requested_workers, "WORKERS", 1, 64)
    if automatic and "adaptive_workers" in item:
        # A retained controller target was valid for the previous deployment.
        # New environment bounds govern it when the container is recreated.
        desired = max(worker_min, min(worker_max, bounded(item["adaptive_workers"], "adaptive workers", 1, 64)))
    requested_threads = saved.get("THREADS") or "4"
    desired_threads = min(thread_max, 4) if requested_threads == "auto" else bounded(requested_threads, "THREADS", 1, 64)
    per_worker_floor = (128 if kind == "query" else 512) * MIB
    worker_capacity = min(worker_max, max(1, math.ceil(cpus)), size // per_worker_floor)
    if worker_capacity < worker_min:
        raise ValueError(f"{item['domain']} {item['label']} cannot fit WORKERS_MIN={worker_min} in its allocated memory.")
    workers = max(worker_min, min(desired, worker_capacity))
    per_worker = size // workers
    thread_capacity = min(thread_max, max(1, per_worker // ((32 if kind == "query" else 128) * MIB)))
    if thread_capacity < thread_min:
        raise ValueError(f"{item['domain']} {item['label']} cannot fit THREADS_MIN={thread_min} in its allocated memory.")
    threads = max(thread_min, min(desired_threads, thread_capacity))
    cache_percent = bounded(value("CACHE_MEMORY_PERCENT"), "CACHE_MEMORY_PERCENT", 5, 80)
    cache_bytes = max(MIB, per_worker * cache_percent // 100)
    corpus = bounded(value("SHARED_CORPUS_LIMIT"), "SHARED_CORPUS_LIMIT", 1, 100000)
    chapter_bytes = cache_bytes * (80 if kind == "query" else 10) // 100
    translation_bytes = cache_bytes * (10 if kind == "query" else 20) // 100
    shared_bytes = cache_bytes - chapter_bytes - translation_bytes
    warm_value = value("WARM_TRANSLATIONS", "").strip().lower()
    warm = [] if warm_value == "none" else list(dict.fromkeys(code.strip() for code in warm_value.split(",") if code.strip()))
    if any(not re.fullmatch(r"[a-z0-9][a-z0-9_-]{0,29}", code) for code in warm):
        raise ValueError("Invalid warm translation code.")
    ttl = bounded(value("MEMORY_CACHE_TTL"), "MEMORY_CACHE_TTL", 0, 31536000)
    jitter = float(value("CACHE_TTL_JITTER"))
    if not 0 <= jitter < 1:
        raise ValueError("CACHE_TTL_JITTER must be in [0, 1).")
    return {
        "WORKERS": workers, "THREADS": threads, "WORKERS_MIN": worker_min,
        "WORKERS_MAX": worker_capacity, "CPU_QUOTA": quota,
        "TASKS_MAX": max(64 if kind == "query" else 128, workers * (threads + 5) + 32),
        "NOFILE": 4096 if kind == "query" else 8192,
        "MEMORY_HIGH": size * 85 // 100, "MEMORY_MAX": size,
        "MEMORY_CACHE_TTL": ttl, "CACHE_TTL_JITTER": jitter,
        "WARM_TRANSLATIONS": ",".join(warm), "SEARCH_MAX_CONCURRENT": threads,
        "EXPENSIVE_CONCURRENT": max(1, threads // 2),
        "TRANSLATION_CACHE_LIMIT": bounded(value("TRANSLATION_CACHE_LIMIT"), "TRANSLATION_CACHE_LIMIT", 1, 100000),
        "SEARCH_CORPUS_LIMIT": corpus, "SHARED_CORPUS_LIMIT": corpus,
        "SHARED_CORPUS_BYTES": shared_bytes, "CHAPTER_CACHE_BYTES": chapter_bytes,
        "TRANSLATION_CACHE_BYTES": translation_bytes,
        "REFERENCE_CACHE_LIMIT": bounded(value("REFERENCE_CACHE_LIMIT"), "REFERENCE_CACHE_LIMIT", 1, 1000000),
        "CHAPTER_CACHE_LIMIT": bounded(value("CHAPTER_CACHE_LIMIT"), "CHAPTER_CACHE_LIMIT", 1, 1000000),
    }


def unit_memory(units: set[str], ctl: str, offline: bool) -> tuple[int, list[dict]]:
    """Inspect actual ceilings, including starting and still-draining units."""
    if offline or not units:
        return 0, []
    # A single systemd query includes active, retiring and interrupted candidates.
    # Active symlinks alone would miss still-serving workers during nginx drain.
    run = subprocess.run([ctl, "show", "--property=Id,ActiveState,MemoryMax", *sorted(units)],
                         capture_output=True, text=True, timeout=20, check=False)
    if run.returncode:
        raise ValueError("Cannot inspect running runtime memory ceilings; ensure systemd is running before applying resources.")
    live = []
    inspected = set()
    for block in run.stdout.strip().split("\n\n"):
        props = dict(line.split("=", 1) for line in block.splitlines() if "=" in line)
        unit, state = props.get("Id"), props.get("ActiveState")
        if unit not in units or unit in inspected or not state:
            raise ValueError("Cannot inspect running runtime memory ceilings; systemd returned incomplete unit state.")
        inspected.add(unit)
        if state in {"inactive", "failed"}:
            continue
        maximum = props.get("MemoryMax", "infinity")
        if not maximum.isdigit() or not 0 < int(maximum) < 2 ** 63:
            raise ValueError(f"Running runtime {props.get('Id', '?')} has no finite memory ceiling; apply its limits before budgeting more services.")
        live.append({"unit": props.get("Id", "?"), "memory_max": int(maximum)})
    if inspected != units:
        raise ValueError("Cannot inspect running runtime memory ceilings; systemd omitted requested units.")
    return sum(item["memory_max"] for item in live), live


def running_memory(entries: list[dict], ctl: str, offline: bool) -> tuple[int, list[dict]]:
    units = {f"getbible-{item['kind']}-{item['label']}-{path.parent.name}.service"
             for item in entries for path in Path(item["root"]).glob("deployments/*/limits.conf")}
    return unit_memory(units, ctl, offline)


def wait_drain(args) -> None:
    """Wait for the existing retirement mechanism; never kill live generations."""
    if args.offline:
        return
    entries = [item for item in inventory(Path(args.registry), Path(args.runtime_root))
               if item["domain"] == args.wait_drain]
    selected = set()
    for item in entries:
        active = Path(item["root"]) / "active"
        if active.is_dir():
            selected.add(f"getbible-{item['kind']}-{item['label']}-{active.resolve().name}.service")
    deadline = time.monotonic() + args.drain_timeout
    while True:
        _, live = running_memory(entries, args.systemctl, False)
        pending = [item["unit"] for item in live if item["unit"] not in selected]
        if not pending:
            return
        if time.monotonic() >= deadline:
            raise ValueError("Previous runtime generations are still draining; they were kept serving. "
                             "Retry resource application when requests finish: " + ", ".join(pending))
        time.sleep(min(2, max(0, deadline - time.monotonic())))


def plan(args) -> dict:
    enabled = args.mode == "docker" or args.budget not in {"", "auto", "off"}
    if args.mode == "docker" and args.budget == "off":
        raise ValueError("Docker resource adaptation cannot be disabled; configure a finite Compose memory limit.")
    if not enabled:
        return {"enabled": False, "source": "native manifest and endpoint settings", "endpoints": []}
    # Runtime services are siblings of the management service, not children
    # inside its 512-MiB cgroup. PID 1 identifies the enclosing system/container
    # budget while preserving every enclosing cgroup ceiling.
    limits = cgroup_limits(Path(args.proc_root), Path(args.cgroup_root) if args.cgroup_root else None, owner="1")
    cap = limits["memory"]
    if args.mode == "docker" and cap is None:
        raise ValueError("Docker requires a finite cgroup v2 memory.max; set the Compose memory limit before starting getBible.")
    requested = None if args.budget in {"", "auto"} else memory_bytes(args.budget)
    physical = host_memory(Path(args.proc_root))
    budget = min(value for value in (cap, requested, physical) if value is not None)
    source = "cgroup" if requested is None else "configured budget"
    if requested is not None and cap is not None and cap < requested:
        source = "cgroup (lower than configured budget)"
    if physical is not None and physical == budget and all(value is None or value > physical for value in (cap, requested)):
        source = "physical memory (lower than configured or cgroup budget)"
    policy = policy_values(args)
    infrastructure = max(256 * MIB, budget * bounded(policy["RESOURCE_RESERVE_PERCENT"], "RESOURCE_RESERVE_PERCENT", 5, 75) // 100)
    # Each MCP domain has a 256-MiB process ceiling. Reserve its
    # serving and candidate generations independently of Bible corpus budgets.
    mcp_reserve, mcp_candidate, mcp_live = mcp_memory(args)
    reserve = infrastructure + mcp_reserve
    available = budget - reserve
    entries = inventory(Path(args.registry), Path(args.runtime_root))
    policy = policy_values(args)
    adaptive_path = Path(getattr(args, "adaptive_state", "/var/lib/getbible/adaptive.json"))
    try:
        adaptive = json.loads(adaptive_path.read_text()).get("targets", {})
    except (OSError, ValueError, AttributeError):
        adaptive = {}
    for item in entries:
        min_key = item["kind"].upper() + "_MEMORY_MIN"
        max_key = item["kind"].upper() + "_MEMORY_MAX"
        minimum = policy[min_key] if min_key in policy["_authoritative"] else item["config"].get("MEMORY_MIN", policy[min_key])
        maximum = policy[max_key] if max_key in policy["_authoritative"] else item["config"].get("MEMORY_MAX", policy[max_key])
        item["minimum"] = memory_bytes(minimum)
        item["maximum"] = 2**63 if maximum == "auto" else memory_bytes(maximum)
        if item["maximum"] < item["minimum"]:
            raise ValueError("MEMORY_MAX cannot be lower than MEMORY_MIN.")
        target = adaptive.get(item["domain"] + "/" + item["label"], {})
        if isinstance(target, dict):
            weight = target.get("weight", WEIGHT[item["kind"]])
            item["weight"] = max(1, min(16, int(weight)))
            if "workers" in target:
                item["adaptive_workers"] = target["workers"]
    sizes, overlap = allocated(entries, 0)
    required = sum(sizes) + overlap
    if available < required:
        raise ValueError(f"Memory budget {budget // MIB} MiB cannot fit the configured endpoints: "
                         f"need {required // MIB} MiB for minimum runtime ceilings and update overlap, "
                         f"plus {reserve // MIB} MiB infrastructure reserve. Existing services were not changed.")
    low, high = 0, max(0, available // MIB)
    while low < high:
        mid = (low + high + 1) // 2
        trial, extra_overlap = allocated(entries, mid * MIB)
        if sum(trial) + extra_overlap <= available:
            low = mid
        else:
            high = mid - 1
    sizes, overlap = allocated(entries, low * MIB)
    effective = []
    for item, size in zip(entries, sizes):
        effective.append({"domain": item["domain"], "label": item["label"], "kind": item["kind"],
                          "requested_warm": item["config"].get("WARM_TRANSLATIONS", ""),
                          "selected_memory_max_bytes": selected_ceiling(item),
                          "settings": endpoint_settings(item, size, limits["cpus"], policy, args.mode)})
    running, live = running_memory(entries, args.systemctl, args.offline) if args.candidate_domain else (None, [])
    candidate = sum(item["settings"]["MEMORY_MAX"] for item in effective if item["domain"] == args.candidate_domain)
    if running is not None:
        live.extend(mcp_live)
        running += sum(item["memory_max"] for item in mcp_live)
        candidate += mcp_candidate
    # Deployment is serialized: reconciliation must first shrink old runtimes
    # before a newly registered MCP domain starts. Admit the current candidate
    # against live ceilings, not memory reserved for future MCP generations.
    admission_available = budget - infrastructure
    if running is not None and running + candidate > admission_available:
        raise ValueError(f"Candidate admission needs {(running + candidate) // MIB} MiB but only {admission_available // MIB} MiB "
                         "is available after infrastructure reserve. A previous generation may still be draining, "
                         "or the memory cap was reduced. Existing services were not changed; retry after drain "
                         "or restore the previous memory budget.")
    return {"enabled": True, "source": source, "budget_bytes": budget,
            "configured_budget": args.budget, "cgroup_limit_bytes": cap,
            "cgroup_limit_path": limits["memory_path"], "cpu_capacity": limits["cpus"],
            "infrastructure_reserve_bytes": reserve, "mcp_reserve_bytes": mcp_reserve,
            "steady_runtime_bytes": sum(sizes),
            "candidate_reserve_bytes": overlap, "running_bytes": running, "running_generations": live,
            "note": "Cache byte budgets bound estimated retained objects; process RSS also includes request work, shared pages and interpreter overhead. Configured warm lists are honored and may evict under a small byte budget. Runtime readiness and cgroup ceilings remain authoritative.",
            "endpoints": effective}


def selected_settings(item: dict) -> dict:
    """Read only resource fields from the selected immutable generation."""
    root = Path(item["root"]) / "active"
    result = {}
    limits = root / "limits.conf"
    mapping = {"MemoryMax": "MEMORY_MAX", "MemoryHigh": "MEMORY_HIGH", "CPUQuota": "CPU_QUOTA",
               "TasksMax": "TASKS_MAX", "LimitNOFILE": "NOFILE"}
    if limits.is_file():
        for line in limits.read_text().splitlines():
            key, separator, value = line.partition("=")
            if separator and key in mapping:
                if key.startswith("Memory") and value not in {"", "infinity"}:
                    value = memory_bytes(value)
                elif key in {"TasksMax", "LimitNOFILE"} and value.isdigit():
                    value = int(value)
                result[mapping[key]] = value
    prefix = item["kind"].upper()
    env_mapping = {f"{prefix}_{key}": key for key in ("WORKERS", "THREADS", "WARM_TRANSLATIONS")}
    env_mapping.update({"GETBIBLE_" + key: key for key in (
        "SHARED_CORPUS_LIMIT", "SHARED_CORPUS_BYTES", "CHAPTER_CACHE_BYTES", "TRANSLATION_CACHE_BYTES",
        "TRANSLATION_CACHE_LIMIT", "CHAPTER_CACHE_LIMIT", "REFERENCE_CACHE_LIMIT", "SEARCH_CORPUS_LIMIT")})
    env_mapping.update(GETBIBLE_CACHE_TTL_SECONDS="MEMORY_CACHE_TTL", GETBIBLE_CACHE_TTL_JITTER="CACHE_TTL_JITTER",
                       SEARCH_MAX_CONCURRENT="SEARCH_MAX_CONCURRENT", SEARCH_MAX_CONCURRENT_EXPENSIVE="EXPENSIVE_CONCURRENT")
    for key, raw in config(root / "runtime.env").items():
        if key not in env_mapping:
            continue
        value = re.sub(r'\\([\\"])', r'\1', raw[1:-1]) if raw.startswith('"') and raw.endswith('"') else raw
        target = env_mapping[key]
        if target == "CACHE_TTL_JITTER":
            value = float(value)
        elif target != "WARM_TRANSLATIONS" and value.isdigit():
            value = int(value)
        result[target] = value
    return result


def management_observations(args) -> dict:
    """Read bounded sampler metadata and the existing read-only capacity view."""
    storage = {"state": "unavailable", "progress": None, "usage": None}
    state = Path(getattr(args, "storage_state", "/var/lib/getbible/storage"))
    now = time.time()
    for filename, key in (("progress.json", "progress"), ("usage.json", "usage")):
        try:
            with (state / filename).open() as stream:
                data = json.loads(stream.read(65537))
            if not isinstance(data, dict):
                continue
            allowed = {"status", "started_at", "completed_at", "generated_at", "updated_at", "used_bytes",
                       "max_age_seconds", "error", "entries", "pending", "files", "directories",
                       "allocated_bytes", "pending_directories", "duration_seconds"}
            storage[key] = {name: value for name, value in data.items() if name in allowed}
        except (OSError, ValueError):
            continue
    usage = storage["usage"] or {}
    observed = usage.get("started_at", usage.get("generated_at"))
    if isinstance(observed, (float, int)):
        age = now - observed
        horizon = usage.get("max_age_seconds", 120)
        storage["age_seconds"] = max(0, age)
        storage["state"] = "fresh" if isinstance(horizon, (int, float)) and 0 <= age <= horizon and usage.get("status", "complete") == "complete" else "stale"
    root = Path(__file__).resolve().parent
    for path in (root / "apps/telemetry", root.parent / "apps/telemetry"):
        if path.is_dir():
            sys.path.insert(0, str(path))
            break
    try:
        from getbible_telemetry.diagnostics import read_capacity
        capacity = read_capacity(getattr(args, "telemetry_db", "/var/lib/getbible/telemetry/traffic.sqlite3"),
                                 getattr(args, "config", "/etc/getbible/getbible.conf"),
                                 getattr(args, "environment", "/run/getbible/environment.conf"))
    except ImportError:
        capacity = {"state": "unavailable", "note": "Capacity reader is not installed; inspect getbible capacity after updating management services."}
    return {"storage_accounting": storage, "capacity": capacity}


def realignment(args) -> dict:
    """Offer a conservative, reviewable allocation without changing policy."""
    proc = Path(args.proc_root)
    limits = cgroup_limits(proc, Path(args.cgroup_root) if args.cgroup_root else None, owner="1")
    physical, available = host_memory(proc), available_memory(proc)
    totals = [value for value in (physical, limits["memory"]) if value is not None]
    total = min(totals) if totals else None
    # MemAvailable can describe the host in a container. The current usage at
    # the limiting ancestor supplies a stricter bound when that value exists.
    if limits["memory_path"]:
        usage = Path(limits["memory_path"]).with_name("memory.current")
        if usage.is_file():
            remaining = max(0, limits["memory"] - int(usage.read_text()))
            available = min(remaining, available) if available is not None else remaining
    hardware = {"physical_memory_bytes": physical, "effective_memory_bytes": total,
                "available_memory_bytes": available, "cgroup_memory_bytes": limits["memory"],
                "cpu_capacity": limits["cpus"], "storage": []}
    for entry in getattr(args, "storage_path", []) or []:
        name, separator, raw = entry.partition("=")
        if not separator or not name or not raw:
            raise ValueError("Storage observations require NAME=PATH.")
        path = Path(raw)
        observation = {"name": name, "path": str(path)}
        try:
            stats = os.statvfs(path)
            observation.update(status="observed", total_bytes=stats.f_blocks * stats.f_frsize,
                               available_bytes=stats.f_bavail * stats.f_frsize,
                               total_inodes=stats.f_files, available_inodes=stats.f_favail)
        except OSError as error:
            observation.update(status="unavailable", error=error.strerror)
        hardware["storage"].append(observation)
    saved = config(Path(getattr(args, "config", "/etc/getbible/getbible.conf")))
    authoritative = set(getattr(args, "authoritative", []) or [])
    owner = "environment" if "MEMORY_BUDGET" in authoritative else "saved global" if "MEMORY_BUDGET" in saved else "default"
    proposed = getattr(args, "realign_budget", None) or args.budget
    reason, assumption = "", "Existing explicit settings remain authoritative; targets are bounded by effective hardware."
    if args.mode == "native" and proposed in {"", "auto", "off"}:
        assumption = ("Native recommendation reserves 25% of effective RAM (at least 256 MiB) from both total and "
                      "currently available RAM. Existing runtime allocations are not counted as reclaimable. "
                      "This is a conservative starting point, not a workload benchmark; use --memory-budget for a deliberate shared-host allocation.")
        reserve = max(256 * MIB, total // 4) if total is not None else None
        if total is None or available is None:
            reason = "Cannot recommend a native budget without total and available memory; provide --memory-budget."
        else:
            recommendation = max(0, min(total, available) - reserve) // MIB
            if recommendation:
                proposed = f"{recommendation}M"
            else:
                reason = "Available memory does not leave the native host reserve; free capacity or provide a deliberate --memory-budget."
    budget_changed = proposed != args.budget
    if budget_changed and owner == "environment":
        reason = "MEMORY_BUDGET is environment-controlled; change GETBIBLE_MEMORY_BUDGET at its deployment source and rerun the plan."
    allocation = None
    proposal = argparse.Namespace(**vars(args))
    proposal.budget = proposed
    try:
        if not reason:
            allocation = plan(proposal)
            if not allocation["enabled"]:
                reason = "Aggregate runtime budgeting is not enabled."
    except (ValueError, OSError, subprocess.SubprocessError) as error:
        reason = str(error)
    comparisons = []
    entries = inventory(Path(args.registry), Path(args.runtime_root))
    policies = policy_values(args)
    for item in entries:
        selected = selected_settings(item)
        target = next((row["settings"] for row in (allocation or {}).get("endpoints", [])
                       if row["domain"] == item["domain"] and row["label"] == item["label"]), {})
        owners = {}
        for key in policies:
            if key.startswith("_") or key.startswith(("QUERY_", "SEARCH_")) and not key.startswith(item["kind"].upper() + "_"):
                continue
            endpoint_key = key.removeprefix(item["kind"].upper() + "_")
            owners[endpoint_key] = ("environment" if key in authoritative else "endpoint" if endpoint_key in item["config"]
                                    else "saved global" if key in saved else "default")
        for key in ("WORKERS", "THREADS"):
            owners[key] = "endpoint" if key in item["config"] else "automatic default"
        ignored = {"WORKERS_MIN", "WORKERS_MAX"}
        if item["kind"] == "query":
            ignored.update(("SEARCH_MAX_CONCURRENT", "EXPENSIVE_CONCURRENT"))
        differences = {key: {"current": selected.get(key), "proposed": value} for key, value in target.items()
                       if key not in ignored and selected.get(key) != value}
        comparisons.append({"domain": item["domain"], "label": item["label"], "kind": item["kind"],
                            "selected": selected, "target": target, "differences": differences, "policy_owners": owners})
    changed = {row["domain"] for row in comparisons if row["differences"]}
    reductions = domain_changes(allocation, True) if allocation else []
    domains = [name for name in reductions if name in changed] + sorted(changed - set(reductions))
    # Exclude changing utilization, filesystem free space and timestamps. The
    # accepted budget and every selected/target resource field remain covered.
    inputs = {"mode": args.mode, "memory": total, "cgroup": limits["memory"], "cpus": limits["cpus"],
              "budget": proposed, "configured_budget": args.budget, "owner": owner,
              "policy": {key: value for key, value in policies.items() if key != "_authoritative"},
              "authoritative": sorted(authoritative), "endpoints": comparisons}
    plan_id = hashlib.sha256(json.dumps(inputs, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
    return {"plan_id": plan_id, "ready": not reason, "status": "blocked" if reason else "ready", "reason": reason,
            "hardware": hardware, "memory_budget": {"current": args.budget, "proposed": proposed, "owner": owner,
                                                     "change": budget_changed, "assumption": assumption},
            "allocation": allocation, "endpoints": comparisons, "domains": domains,
            "management": management_observations(args),
            "limitations": ["Storage figures are filesystem availability, not corpus usage; no data tree is scanned and no storage quota is changed.",
                            "Storage guard and telemetry collector retain separate service limits. Runtime realignment does not repair their failures or raise those limits.",
                            "Deployment CPU/memory caps remain operator-owned. Measurements under representative traffic determine throughput; this plan is not a universal optimum.",
                            "Apply uses normal runtime deployments for the listed domains and the installed manager's current code/configuration; it may also bring those domains to the installed runtime code version.",
                            "Selected settings describe the active generation files; normal readiness and live cgroup overlap checks remain required during apply."]}


def print_realignment(result: dict) -> None:
    hardware, budget = result["hardware"], result["memory_budget"]
    def mib(value):
        return "unknown" if value is None else f"{value // MIB} MiB"
    print(f"Hardware realignment: {result['status']}; plan {result['plan_id']}")
    print(f"Effective CPU: {hardware['cpu_capacity']:g}; RAM: {mib(hardware['effective_memory_bytes'])}; currently available: {mib(hardware['available_memory_bytes'])}")
    print(f"Memory budget: {budget['current']} -> {budget['proposed']} (owner: {budget['owner']})")
    print(budget["assumption"])
    for row in result["endpoints"]:
        print(f"  {row['domain']} {row['label']} ({row['kind']}): {len(row['differences'])} resource changes")
        for key, change in row["differences"].items():
            print(f"    {key}: {change['current'] if change['current'] is not None else 'unknown'} -> {change['proposed']}")
        print("    Policy owners: " + ", ".join(f"{key}={value}" for key, value in row["policy_owners"].items()
                                                if value in {"environment", "endpoint"}))
    for row in hardware["storage"]:
        if row["status"] == "observed":
            print(f"  Storage {row['name']}: {mib(row['available_bytes'])} available / {mib(row['total_bytes'])}; {row['available_inodes']} free inodes")
        else:
            print(f"  Storage {row['name']}: observation unavailable ({row['error']})")
    management = result.get("management", {})
    storage = management.get("storage_accounting", {})
    print(f"Storage accounting: {storage.get('state', 'unavailable')}; sampler progress: {(storage.get('progress') or {}).get('status', 'unavailable')}; age: {storage.get('age_seconds', 'unknown')} seconds")
    capacity = management.get("capacity", {})
    collection = capacity.get("collection", {})
    reclamation = collection.get("reclamation", {})
    print(f"Capacity evidence: {capacity.get('state', 'unavailable')}; collection: {collection.get('state', 'unknown')}; reclamation: {reclamation.get('state', 'unknown')}")
    if capacity.get("note"):
        print(capacity["note"])
    if reclamation.get("reason"):
        print("Reclamation: " + reclamation["reason"])
    for row in capacity.get("limits", []):
        advice = row.get("recommendation", {})
        print(f"  {row.get('label', row.get('id', 'Capacity'))}: {advice.get('status', 'unknown')}; {advice.get('reason', '')}")
    if result["reason"]:
        print("Blocked: " + result["reason"])
    for note in result["limitations"]:
        print(note)
    print("No settings changed. Use resources realign --apply to apply a freshly checked plan.")


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--mode", choices=("native", "docker"), default="native")
    parser.add_argument("--budget", default="auto")
    parser.add_argument("--realign", action="store_true", help="Read-only hardware and selected-versus-target review.")
    parser.add_argument("--realign-budget", help="Explicit budget to review; does not save configuration.")
    parser.add_argument("--config", default="/etc/getbible/getbible.conf")
    parser.add_argument("--storage-path", action="append", default=[], metavar="NAME=PATH")
    parser.add_argument("--storage-state", default="/var/lib/getbible/storage")
    parser.add_argument("--telemetry-db", default="/var/lib/getbible/telemetry/traffic.sqlite3")
    parser.add_argument("--environment", default="/run/getbible/environment.conf")
    parser.add_argument("--policy", action="append", default=[], metavar="KEY=VALUE")
    parser.add_argument("--authoritative", action="append", default=[])
    parser.add_argument("--adaptive-state", default="/var/lib/getbible/adaptive.json")
    parser.add_argument("--registry", default="/etc/getbible/endpoints")
    parser.add_argument("--runtime-root", default="/opt/getbible")
    parser.add_argument("--proc-root", default="/proc")
    parser.add_argument("--cgroup-root")
    parser.add_argument("--systemctl", default="systemctl")
    parser.add_argument("--offline", action="store_true", help="Bootstrap before systemd starts; no running generations exist.")
    parser.add_argument("--candidate-domain")
    parser.add_argument("--exclude-domain", default="")
    parser.add_argument("--wait-drain", metavar="DOMAIN")
    parser.add_argument("--drain-timeout", type=int, default=60)
    parser.add_argument("--select", nargs=2, metavar=("DOMAIN", "ENDPOINT"))
    parser.add_argument("--format", choices=("json", "text", "env", "domains", "reductions", "changes"), default="text")
    args = parser.parse_args()
    try:
        if args.realign:
            if args.format not in {"json", "text"}:
                raise ValueError("Realignment supports text or JSON output.")
            result = realignment(args)
            if args.format == "json":
                print(json.dumps(result, indent=2))
            else:
                print_realignment(result)
            return 0
        if args.wait_drain:
            wait_drain(args)
            return 0
        result = plan(args)
        if args.format == "json":
            print(json.dumps(result, indent=2))
        elif args.format == "domains":
            first = domain_changes(result, decreases_only=True)
            rest = [item["domain"] for item in result["endpoints"] if item["domain"] not in first]
            print("\n".join(dict.fromkeys(first + rest)))
        elif args.format in {"reductions", "changes"}:
            print("\n".join(domain_changes(result, args.format == "reductions", args.exclude_domain)))
        elif args.format == "env":
            if not args.select:
                raise ValueError("--format env requires --select DOMAIN ENDPOINT")
            print(f"RES_ENABLED={'true' if result['enabled'] else 'false'}")
            if result["enabled"]:
                item = next((item for item in result["endpoints"] if [item["domain"], item["label"]] == args.select), None)
                if item is None:
                    raise ValueError("The selected runtime endpoint is not enabled in the registry.")
                for key, value in item["settings"].items():
                    print(f"RES_{key}={value}")
        else:
            print(f"Resource allocation: {result['source']}")
            if result["enabled"]:
                print(f"Total budget: {result['budget_bytes'] // MIB} MiB; infrastructure reserve: "
                      f"{result['infrastructure_reserve_bytes'] // MIB} MiB; runtime ceilings: "
                      f"{result['steady_runtime_bytes'] // MIB} MiB; update overlap: {result['candidate_reserve_bytes'] // MIB} MiB")
                print(f"CPU capacity: {result['cpu_capacity']:g}; cgroup cap: {result['cgroup_limit_path'] or 'none'}")
                for item in result["endpoints"]:
                    settings = item["settings"]
                    print(f"  {item['domain']} {item['label']} ({item['kind']}): "
                          f"{settings['MEMORY_MAX'] // MIB} MiB, {settings['WORKERS']} workers x "
                          f"{settings['THREADS']} threads; warm: {settings['WARM_TRANSLATIONS'] or '-'}")
                print(result["note"])
                print("These are calculated targets. Existing generations change on apply or container recreation.")
        return 0
    except (ValueError, OSError, subprocess.SubprocessError) as exc:
        print(f"Resource configuration: {exc}", file=sys.stderr)
        return 1


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