"""
AI Agent tool adoption approval package snapshot.

Loads the latest committed, read-only approval package for adopting tools such
as Renovate, OSV-Scanner, Trivy, Syft, and Grype. This module never installs
tools, writes CI workflows, downloads vulnerability databases, queries
registries, creates PRs, sends Telegram messages, or changes production.
"""

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_tool_adoption_approval_package_*.json"
_SCHEMA_VERSION = "ai_agent_tool_adoption_approval_package_v1"
_RUNTIME_AUTHORITY = "approval_package_only_no_tool_install_or_ci_change"


def load_latest_ai_agent_tool_adoption_approval_package(
    evaluations_dir: Path | None = None,
) -> dict[str, Any]:
    """Load the newest committed AI Agent tool adoption approval package."""
    directory = evaluations_dir or _DEFAULT_EVALUATIONS_DIR
    candidates = sorted(directory.glob(_SNAPSHOT_PATTERN))
    if not candidates:
        raise FileNotFoundError(
            f"no AI Agent tool adoption approval package 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_rollup_consistency(payload, str(latest))
    _require_tool_safety(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")
    if program_status.get("runtime_authority") != _RUNTIME_AUTHORITY:
        raise ValueError(f"{label}: runtime_authority must stay {_RUNTIME_AUTHORITY}")

    boundaries = payload.get("approval_boundaries") or {}
    blocked_flags = {
        "tool_install_allowed",
        "ci_workflow_change_allowed",
        "external_registry_lookup_allowed",
        "vulnerability_database_download_allowed",
        "package_upgrade_allowed",
        "lockfile_write_allowed",
        "docker_build_allowed",
        "image_pull_allowed",
        "gitea_pr_creation_allowed",
        "auto_merge_allowed",
        "telegram_direct_send_allowed",
        "paid_service_enabled",
        "production_route_change_allowed",
        "secret_plaintext_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_rollup_consistency(payload: dict[str, Any], label: str) -> None:
    tools = payload.get("tool_candidates") or []
    sources = payload.get("source_evidence") or []
    lanes = payload.get("adoption_lanes") or []
    rollups = payload.get("rollups") or {}

    expected_counts = {
        "tool_count": len(tools),
        "source_evidence_count": len(sources),
        "adoption_lane_count": len(lanes),
    }
    mismatched = {
        key: {"expected": expected, "actual": rollups.get(key)}
        for key, expected in expected_counts.items()
        if rollups.get(key) != expected
    }
    if mismatched:
        raise ValueError(f"{label}: rollup counts must match payload sections: {mismatched}")

    expected_lists = {
        "approval_required_tool_ids": sorted(
            tool.get("tool_id")
            for tool in tools
            if tool.get("adoption_status") == "approval_required"
        ),
        "ci_change_required_tool_ids": sorted(
            tool.get("tool_id") for tool in tools if tool.get("ci_change_required") is True
        ),
        "secret_required_tool_ids": sorted(
            tool.get("tool_id") for tool in tools if _requires_secret_review(tool)
        ),
        "external_data_required_tool_ids": sorted(
            tool.get("tool_id") for tool in tools if _requires_external_data_gate(tool)
        ),
    }
    for key, expected in expected_lists.items():
        if sorted(rollups.get(key) or []) != expected:
            raise ValueError(f"{label}: rollups.{key} mismatch")

    zero_rollups = {
        "tool_install_allowed_count",
        "ci_change_allowed_count",
        "auto_merge_allowed_count",
        "telegram_direct_send_count",
    }
    nonzero = sorted(key for key in zero_rollups if rollups.get(key) != 0)
    if nonzero:
        raise ValueError(f"{label}: rollout safety counters must remain 0: {nonzero}")


def _require_tool_safety(payload: dict[str, Any], label: str) -> None:
    source_ids = {source.get("source_id") for source in payload.get("source_evidence") or []}
    unsafe_tools = [
        tool.get("tool_id")
        for tool in payload.get("tool_candidates") or []
        if tool.get("adoption_status") != "approval_required"
        or not tool.get("approval_requirements")
        or not tool.get("blocked_until_approval")
        or not set(tool.get("official_source_refs") or []).issubset(source_ids)
        or not tool.get("rollback_plan")
    ]
    if unsafe_tools:
        raise ValueError(f"{label}: tools must stay approval-bound: {unsafe_tools}")

    unsafe_lanes = [
        lane.get("lane_id")
        for lane in payload.get("adoption_lanes") or []
        if not lane.get("approval_gate") or not lane.get("blocked_now")
    ]
    if unsafe_lanes:
        raise ValueError(f"{label}: adoption lanes need approval gates: {unsafe_lanes}")

    missing_required_fields = [
        field.get("field_id")
        for field in payload.get("approval_packet_fields") or []
        if field.get("required") is True and not field.get("description")
    ]
    if missing_required_fields:
        raise ValueError(f"{label}: approval fields need descriptions: {missing_required_fields}")


def _requires_secret_review(tool: dict[str, Any]) -> bool:
    requirement = str(tool.get("secret_requirement") or "").lower()
    return "credentials" in requirement or "token" in requirement


def _requires_external_data_gate(tool: dict[str, Any]) -> bool:
    requirement = str(tool.get("external_data_requirement") or "").lower()
    if requirement.startswith("no external"):
        return False
    return (
        "currently blocked" in requirement
        or "metadata required" in requirement
        or "database required" in requirement
        or "db required" in requirement
    )
