"""
AI Agent automation inventory snapshot.

Loads the latest committed, read-only inventory snapshot for services, tools,
packages, backups, AI providers, workflows, observability, and security
boundaries. This module never calls external sources and never approves writes.
"""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any

from src.services.snapshot_paths import default_evaluations_dir

_DEFAULT_EVALUATIONS_DIR = default_evaluations_dir(Path(__file__))
_SNAPSHOT_PATTERN = "ai_agent_automation_inventory_snapshot_*.json"
_SCHEMA_VERSION = "ai_agent_automation_inventory_snapshot_v1"


def load_latest_ai_agent_automation_inventory_snapshot(
    evaluations_dir: Path | None = None,
) -> dict[str, Any]:
    """Load the newest committed AI Agent automation inventory snapshot."""
    directory = evaluations_dir or _DEFAULT_EVALUATIONS_DIR
    candidates = sorted(directory.glob(_SNAPSHOT_PATTERN))
    if not candidates:
        raise FileNotFoundError(f"no AI Agent automation inventory snapshots found in {directory}")

    latest = candidates[-1]
    with latest.open(encoding="utf-8") as handle:
        payload = json.load(handle)

    if not isinstance(payload, dict):
        raise ValueError(f"{latest}: expected JSON object")
    _require_schema(payload, _SCHEMA_VERSION, str(latest))
    _require_read_only_boundaries(payload, str(latest))
    _require_task_approval_boundaries(payload, str(latest))
    return payload


def _require_schema(payload: dict[str, Any], expected: str, label: str) -> None:
    actual = payload.get("schema_version")
    if actual != expected:
        raise ValueError(f"{label}: expected schema_version={expected}, got {actual!r}")


def _require_read_only_boundaries(payload: dict[str, Any], label: str) -> None:
    program_status = payload.get("program_status") or {}
    if program_status.get("read_only_mode") is not True:
        raise ValueError(f"{label}: program_status.read_only_mode must be true")

    boundaries = payload.get("approval_boundaries") or {}
    blocked_flags = {
        "sdk_installation_allowed",
        "paid_api_call_allowed",
        "shadow_or_canary_allowed",
        "production_routing_allowed",
        "destructive_operation_allowed",
    }
    allowed = sorted(flag for flag in blocked_flags if boundaries.get(flag) is not False)
    if allowed:
        raise ValueError(f"{label}: approval boundaries must remain false: {allowed}")


def _require_task_approval_boundaries(payload: dict[str, Any], label: str) -> None:
    tasks = payload.get("tasks") or []
    missing = sorted(task.get("task_id") for task in tasks if not task.get("approval_boundary"))
    if missing:
        raise ValueError(f"{label}: tasks must include approval_boundary: {missing}")

    mismatched_modes = sorted(
        task.get("task_id")
        for task in tasks
        if (task.get("approval_boundary") or {}).get("mode") != task.get("gate_status")
    )
    if mismatched_modes:
        raise ValueError(f"{label}: approval_boundary.mode must match gate_status: {mismatched_modes}")

    missing_blocked_actions = sorted(
        task.get("task_id")
        for task in tasks
        if not (task.get("approval_boundary") or {}).get("blocked_actions")
    )
    if missing_blocked_actions:
        raise ValueError(f"{label}: approval_boundary.blocked_actions must be non-empty: {missing_blocked_actions}")

    rollup = payload.get("task_approval_boundary_rollup") or {}
    if rollup.get("total_tasks") != len(tasks):
        raise ValueError(f"{label}: task_approval_boundary_rollup.total_tasks must match tasks")

    by_mode: dict[str, int] = {}
    for task in tasks:
        mode = (task.get("approval_boundary") or {}).get("mode")
        by_mode[mode] = by_mode.get(mode, 0) + 1
    if rollup.get("by_mode") != by_mode:
        raise ValueError(f"{label}: task_approval_boundary_rollup.by_mode must match tasks")

    explicit_approval = sorted(
        task.get("task_id")
        for task in tasks
        if (task.get("approval_boundary") or {}).get("mode") != "read_only_allowed"
    )
    if sorted(rollup.get("tasks_requiring_explicit_approval") or []) != explicit_approval:
        raise ValueError(
            f"{label}: task_approval_boundary_rollup.tasks_requiring_explicit_approval must match tasks"
        )

    with_blocked_operations = sorted(
        task.get("task_id")
        for task in tasks
        if (task.get("approval_boundary") or {}).get("blocked_actions")
    )
    if sorted(rollup.get("tasks_with_blocked_operations") or []) != with_blocked_operations:
        raise ValueError(
            f"{label}: task_approval_boundary_rollup.tasks_with_blocked_operations must match tasks"
        )
