from __future__ import annotations

import json

import pytest

from src.services.ai_agent_tool_adoption_approval_package import (
    load_latest_ai_agent_tool_adoption_approval_package,
)


def test_load_latest_ai_agent_tool_adoption_approval_package_reads_committed_snapshot():
    data = load_latest_ai_agent_tool_adoption_approval_package()

    assert data["schema_version"] == "ai_agent_tool_adoption_approval_package_v1"
    assert data["program_status"]["overall_completion_percent"] == 55
    assert data["program_status"]["current_task_id"] == "P2-402C"
    assert data["program_status"]["next_task_id"] == "P2-402D"
    assert data["program_status"]["read_only_mode"] is True
    assert (
        data["program_status"]["runtime_authority"]
        == "approval_package_only_no_tool_install_or_ci_change"
    )
    assert data["approval_boundaries"]["tool_install_allowed"] is False
    assert data["approval_boundaries"]["ci_workflow_change_allowed"] is False
    assert data["approval_boundaries"]["external_registry_lookup_allowed"] is False
    assert data["approval_boundaries"]["vulnerability_database_download_allowed"] is False
    assert data["approval_boundaries"]["gitea_pr_creation_allowed"] is False
    assert data["approval_boundaries"]["telegram_direct_send_allowed"] is False
    assert data["rollups"]["tool_count"] == len(data["tool_candidates"]) == 5
    assert data["rollups"]["source_evidence_count"] == len(data["source_evidence"]) == 5
    assert data["rollups"]["adoption_lane_count"] == len(data["adoption_lanes"]) == 4
    assert data["rollups"]["tool_install_allowed_count"] == 0
    assert data["rollups"]["ci_change_allowed_count"] == 0
    assert data["rollups"]["auto_merge_allowed_count"] == 0
    assert data["rollups"]["telegram_direct_send_count"] == 0
    assert set(data["rollups"]["approval_required_tool_ids"]) == {
        "renovate_gitea",
        "osv_scanner",
        "trivy",
        "syft",
        "grype",
    }
    assert set(data["rollups"]["secret_required_tool_ids"]) == {
        "renovate_gitea",
        "trivy",
        "syft",
        "grype",
    }
    assert "syft" not in data["rollups"]["external_data_required_tool_ids"]


def test_ai_agent_tool_adoption_approval_package_rejects_tool_install_allowed(tmp_path):
    snapshot = _snapshot()
    snapshot["approval_boundaries"]["tool_install_allowed"] = True
    (tmp_path / "ai_agent_tool_adoption_approval_package_2026-06-11.json").write_text(
        json.dumps(snapshot),
        encoding="utf-8",
    )

    with pytest.raises(ValueError, match="approval boundaries"):
        load_latest_ai_agent_tool_adoption_approval_package(tmp_path)


def test_ai_agent_tool_adoption_approval_package_rejects_rollup_mismatch(tmp_path):
    snapshot = _snapshot()
    snapshot["rollups"]["tool_count"] = 99
    (tmp_path / "ai_agent_tool_adoption_approval_package_2026-06-11.json").write_text(
        json.dumps(snapshot),
        encoding="utf-8",
    )

    with pytest.raises(ValueError, match="rollup counts"):
        load_latest_ai_agent_tool_adoption_approval_package(tmp_path)


def test_ai_agent_tool_adoption_approval_package_rejects_non_approval_tool(tmp_path):
    snapshot = _snapshot()
    snapshot["tool_candidates"][0]["adoption_status"] = "enabled"
    snapshot["rollups"]["approval_required_tool_ids"] = []
    (tmp_path / "ai_agent_tool_adoption_approval_package_2026-06-11.json").write_text(
        json.dumps(snapshot),
        encoding="utf-8",
    )

    with pytest.raises(ValueError, match="approval-bound"):
        load_latest_ai_agent_tool_adoption_approval_package(tmp_path)


def test_ai_agent_tool_adoption_approval_package_rejects_unknown_source_ref(tmp_path):
    snapshot = _snapshot()
    snapshot["tool_candidates"][0]["official_source_refs"] = ["unknown_source"]
    (tmp_path / "ai_agent_tool_adoption_approval_package_2026-06-11.json").write_text(
        json.dumps(snapshot),
        encoding="utf-8",
    )

    with pytest.raises(ValueError, match="approval-bound"):
        load_latest_ai_agent_tool_adoption_approval_package(tmp_path)


def _snapshot() -> dict:
    return {
        "schema_version": "ai_agent_tool_adoption_approval_package_v1",
        "generated_at": "2026-06-11T23:35:00+08:00",
        "program_status": {
            "overall_completion_percent": 55,
            "current_priority": "P2",
            "current_task_id": "P2-402C",
            "next_task_id": "P2-402D",
            "read_only_mode": True,
            "runtime_authority": "approval_package_only_no_tool_install_or_ci_change",
            "status_note": "測試。",
        },
        "source_evidence": [
            {
                "source_id": "renovate_gitea_platform_docs",
                "tool_id": "renovate_gitea",
                "name": "Renovate Gitea platform docs",
                "url": "https://docs.renovatebot.com/modules/platform/gitea/",
                "retrieved_at": "2026-06-11T23:35:00+08:00",
                "evidence_type": "official_documentation",
                "usage_boundary": "測試。",
            }
        ],
        "agent_review_matrix": [
            {
                "agent_id": "openclaw",
                "role": "測試。",
                "allowed_now": ["讀取批准包"],
                "blocked_until_approval": ["安裝工具"],
                "output": "verdict",
            }
        ],
        "adoption_lanes": [
            {
                "lane_id": "dependency_update_pr_lane",
                "display_name": "Dependency update PR lane",
                "owner_agent": "hermes",
                "tool_ids": ["renovate_gitea"],
                "approval_gate": "approval_required",
                "planned_output": "approval package",
                "blocked_now": ["PR creation"],
            }
        ],
        "tool_candidates": [
            {
                "tool_id": "renovate_gitea",
                "display_name": "Renovate for Gitea",
                "category": "dependency_update_pr",
                "owner_agent": "hermes",
                "adoption_status": "approval_required",
                "risk_tier": "high",
                "cost_profile": "runner cost requires approval",
                "secret_requirement": "Gitea bot token required after approval.",
                "external_data_requirement": "Package registry metadata required after approval; currently blocked.",
                "ci_change_required": True,
                "official_source_refs": ["renovate_gitea_platform_docs"],
                "intended_scope": ["dependency update PR draft"],
                "approval_requirements": ["bot token storage plan"],
                "blocked_until_approval": ["PR creation"],
                "recommendation": "測試。",
                "rollback_plan": "測試。",
            }
        ],
        "approval_packet_fields": [
            {
                "field_id": "operator_approval_id",
                "required": True,
                "owner_agent": "openclaw",
                "description": "測試。",
            }
        ],
        "approval_boundaries": {
            "tool_install_allowed": False,
            "ci_workflow_change_allowed": False,
            "external_registry_lookup_allowed": False,
            "vulnerability_database_download_allowed": False,
            "package_upgrade_allowed": False,
            "lockfile_write_allowed": False,
            "docker_build_allowed": False,
            "image_pull_allowed": False,
            "gitea_pr_creation_allowed": False,
            "auto_merge_allowed": False,
            "telegram_direct_send_allowed": False,
            "paid_service_enabled": False,
            "production_route_change_allowed": False,
            "secret_plaintext_allowed": False,
        },
        "rollups": {
            "tool_count": 1,
            "source_evidence_count": 1,
            "adoption_lane_count": 1,
            "approval_required_tool_ids": ["renovate_gitea"],
            "ci_change_required_tool_ids": ["renovate_gitea"],
            "secret_required_tool_ids": ["renovate_gitea"],
            "external_data_required_tool_ids": ["renovate_gitea"],
            "sbom_tool_ids": [],
            "vulnerability_scan_tool_ids": [],
            "update_pr_tool_ids": ["renovate_gitea"],
            "tool_install_allowed_count": 0,
            "ci_change_allowed_count": 0,
            "auto_merge_allowed_count": 0,
            "telegram_direct_send_count": 0,
            "next_approval_task_ids": ["P2-402D"],
        },
    }
