from __future__ import annotations

import json

import pytest

from src.services.package_supply_chain_inventory import load_latest_package_supply_chain_inventory


def test_load_latest_package_supply_chain_inventory_reads_newest_file(tmp_path):
    older = _snapshot(generated_at="2026-06-03T00:00:00+08:00", completion=91)
    newer = _snapshot(generated_at="2026-06-04T00:00:00+08:00", completion=93)
    (tmp_path / "package_supply_chain_inventory_2026-06-03.json").write_text(
        json.dumps(older),
        encoding="utf-8",
    )
    (tmp_path / "package_supply_chain_inventory_2026-06-04.json").write_text(
        json.dumps(newer),
        encoding="utf-8",
    )

    loaded = load_latest_package_supply_chain_inventory(tmp_path)

    assert loaded["generated_at"] == "2026-06-04T00:00:00+08:00"
    assert loaded["program_status"]["overall_completion_percent"] == 93
    assert loaded["rollups"]["total_surfaces"] == 3
    assert loaded["operation_boundaries"]["dependency_installation_allowed"] is False


def test_package_supply_chain_inventory_requires_read_only_mode(tmp_path):
    snapshot = _snapshot()
    snapshot["program_status"]["read_only_mode"] = False
    (tmp_path / "package_supply_chain_inventory_2026-06-04.json").write_text(
        json.dumps(snapshot),
        encoding="utf-8",
    )

    with pytest.raises(ValueError, match="read_only_mode"):
        load_latest_package_supply_chain_inventory(tmp_path)


def test_package_supply_chain_inventory_requires_blocked_operations(tmp_path):
    snapshot = _snapshot()
    snapshot["operation_boundaries"]["package_upgrade_allowed"] = True
    (tmp_path / "package_supply_chain_inventory_2026-06-04.json").write_text(
        json.dumps(snapshot),
        encoding="utf-8",
    )

    with pytest.raises(ValueError, match="operation boundaries"):
        load_latest_package_supply_chain_inventory(tmp_path)


def test_package_supply_chain_inventory_requires_total_rollup_consistency(tmp_path):
    snapshot = _snapshot()
    snapshot["rollups"]["total_surfaces"] = 999
    (tmp_path / "package_supply_chain_inventory_2026-06-04.json").write_text(
        json.dumps(snapshot),
        encoding="utf-8",
    )

    with pytest.raises(ValueError, match="total_surfaces"):
        load_latest_package_supply_chain_inventory(tmp_path)


def test_package_supply_chain_inventory_requires_action_required_consistency(tmp_path):
    snapshot = _snapshot()
    snapshot["rollups"]["action_required_surface_ids"] = []
    (tmp_path / "package_supply_chain_inventory_2026-06-04.json").write_text(
        json.dumps(snapshot),
        encoding="utf-8",
    )

    with pytest.raises(ValueError, match="action_required_surface_ids"):
        load_latest_package_supply_chain_inventory(tmp_path)


def test_package_supply_chain_inventory_fails_when_missing(tmp_path):
    with pytest.raises(FileNotFoundError):
        load_latest_package_supply_chain_inventory(tmp_path)


def _snapshot(
    *,
    generated_at: str = "2026-06-04T00:00:00+08:00",
    completion: int = 93,
) -> dict:
    return {
        "schema_version": "package_supply_chain_inventory_v1",
        "generated_at": generated_at,
        "program_status": {
            "overall_completion_percent": completion,
            "current_priority": "P1",
            "current_task_id": "P1-201",
            "next_task_id": "P1-202",
            "read_only_mode": True,
        },
        "source_refs": ["apps/api/pyproject.toml"],
        "rollups": {
            "total_surfaces": 3,
            "by_ecosystem": {"python": 2, "javascript": 1},
            "by_status": {"ready": 1, "action_required": 1, "planned_next": 1},
            "python_manifest_count": 2,
            "javascript_manifest_count": 1,
            "docker_surface_count": 0,
            "action_required_surface_ids": ["apps_api_requirements"],
            "planned_next_surface_ids": ["apps_web_package_json"],
        },
        "surfaces": [
            _surface("apps_api_pyproject", "python", "ready"),
            _surface("apps_api_requirements", "python", "action_required"),
            _surface("apps_web_package_json", "javascript", "planned_next"),
        ],
        "drift_findings": [
            {
                "finding_id": "api_python_manifest_drift",
                "severity": "high",
                "status": "action_required",
                "summary": "drift",
                "evidence_refs": ["apps/api/requirements.txt"],
                "next_action": "review",
            }
        ],
        "operation_boundaries": {
            "read_only_api_allowed": True,
            "dependency_installation_allowed": False,
            "package_upgrade_allowed": False,
            "lockfile_write_allowed": False,
            "external_cve_lookup_allowed": False,
            "image_rebuild_allowed": False,
            "production_routing_allowed": False,
        },
        "approval_boundaries": {
            "sdk_installation_allowed": False,
            "paid_api_call_allowed": False,
            "shadow_or_canary_allowed": False,
            "production_routing_allowed": False,
            "destructive_operation_allowed": False,
        },
    }


def _surface(surface_id: str, ecosystem: str, status: str) -> dict:
    return {
        "surface_id": surface_id,
        "display_name": surface_id,
        "ecosystem": ecosystem,
        "status": status,
        "risk_level": "high" if status == "action_required" else "medium",
        "manifest_ref": "manifest",
        "lockfile_ref": "none",
        "direct_dependency_count": 1,
        "optional_dependency_group_count": 0,
        "pinning_policy": "range",
        "runtime_ref": "runtime",
        "gate_status": "read_only_allowed",
        "evidence_refs": ["manifest"],
        "next_action": "next",
    }
