from __future__ import annotations

import json

import pytest

from src.services.ai_agent_automation_inventory_snapshot import (
    load_latest_ai_agent_automation_inventory_snapshot,
)


def test_load_latest_inventory_snapshot_reads_newest_file(tmp_path):
    older = _snapshot(generated_at="2026-06-03T00:00:00+08:00", completion=45)
    newer = _snapshot(generated_at="2026-06-04T00:00:00+08:00", completion=53)
    (tmp_path / "ai_agent_automation_inventory_snapshot_2026-06-03.json").write_text(
        json.dumps(older),
        encoding="utf-8",
    )
    (tmp_path / "ai_agent_automation_inventory_snapshot_2026-06-04.json").write_text(
        json.dumps(newer),
        encoding="utf-8",
    )

    loaded = load_latest_ai_agent_automation_inventory_snapshot(tmp_path)

    assert loaded["generated_at"] == "2026-06-04T00:00:00+08:00"
    assert loaded["program_status"]["overall_completion_percent"] == 53
    assert loaded["approval_boundaries"]["paid_api_call_allowed"] is False
    assert loaded["task_approval_boundary_rollup"]["total_tasks"] == 1


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

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


def test_load_inventory_snapshot_requires_blocked_approval_boundaries(tmp_path):
    snapshot = _snapshot()
    snapshot["approval_boundaries"]["production_routing_allowed"] = True
    (tmp_path / "ai_agent_automation_inventory_snapshot_2026-06-04.json").write_text(
        json.dumps(snapshot),
        encoding="utf-8",
    )

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


def test_load_inventory_snapshot_requires_task_approval_boundaries(tmp_path):
    snapshot = _snapshot()
    del snapshot["tasks"][0]["approval_boundary"]
    (tmp_path / "ai_agent_automation_inventory_snapshot_2026-06-04.json").write_text(
        json.dumps(snapshot),
        encoding="utf-8",
    )

    with pytest.raises(ValueError, match="approval_boundary"):
        load_latest_ai_agent_automation_inventory_snapshot(tmp_path)


def test_load_inventory_snapshot_requires_task_boundary_rollup_consistency(tmp_path):
    snapshot = _snapshot()
    snapshot["task_approval_boundary_rollup"]["by_mode"]["approval_required"] = 1
    (tmp_path / "ai_agent_automation_inventory_snapshot_2026-06-04.json").write_text(
        json.dumps(snapshot),
        encoding="utf-8",
    )

    with pytest.raises(ValueError, match="by_mode"):
        load_latest_ai_agent_automation_inventory_snapshot(tmp_path)


def test_load_inventory_snapshot_fails_when_missing(tmp_path):
    with pytest.raises(FileNotFoundError):
        load_latest_ai_agent_automation_inventory_snapshot(tmp_path)


def _snapshot(
    *,
    generated_at: str = "2026-06-04T00:00:00+08:00",
    completion: int = 53,
) -> dict:
    return {
        "schema_version": "ai_agent_automation_inventory_snapshot_v1",
        "generated_at": generated_at,
        "program_status": {
            "overall_completion_percent": completion,
            "current_priority": "P0",
            "current_task_id": "P0-005",
            "next_task_id": "P0-006",
            "read_only_mode": True,
        },
        "status_taxonomy": {
            "task_statuses": ["planned", "in_progress", "blocked", "done"],
            "gate_statuses": ["read_only_allowed", "approval_required"],
            "priorities": ["P0", "P1", "P2", "P3"],
        },
        "agent_roles": [
            {
                "agent_id": "openclaw",
                "display_name": "OpenClaw",
                "primary_role": "生產仲裁者",
                "allowed_actions": ["只讀診斷"],
                "blocked_actions": ["未批准的生產寫入"],
            }
        ],
        "asset_domains": [
            {
                "domain_id": "services",
                "display_name": "服務",
                "description": "API / Web / Worker",
            }
        ],
        "assets": [
            {
                "asset_id": "awoooi_api",
                "domain_id": "services",
                "display_name": "AWOOOI API",
                "asset_type": "api",
                "status": "in_progress",
                "gate_status": "read_only_allowed",
                "owner_agent": "openclaw",
                "risk_level": "high",
                "evidence_refs": ["apps/api/"],
                "next_action": "建立只讀 API。",
            }
        ],
        "workstreams": [
            {
                "workstream_id": "WS1",
                "display_name": "資產盤點",
                "completion_percent": 55,
                "status": "in_progress",
                "next_task_id": "P0-006",
            }
        ],
        "tasks": [
            {
                "task_id": "P0-005",
                "priority": "P0",
                "status": "done",
                "completion_percent": 100,
                "owner_agent": "hermes",
                "title": "建立靜態盤點種子",
                "output": "seed",
                "gate_status": "read_only_allowed",
                "approval_boundary": {
                    "mode": "read_only_allowed",
                    "display_summary": "只讀呈現 committed snapshot，不授權任何寫入。",
                    "allowed_actions": ["讀取 committed snapshot", "顯示治理 UI"],
                    "blocked_actions": ["production_write", "paid_api_call", "destructive_operation"],
                    "requires_operator_approval_for": ["任何非只讀操作"],
                },
                "next_action": "建立只讀 API。",
            }
        ],
        "task_approval_boundary_rollup": {
            "total_tasks": 1,
            "by_mode": {"read_only_allowed": 1},
            "tasks_requiring_explicit_approval": [],
            "tasks_with_blocked_operations": ["P0-005"],
        },
        "evidence": [
            {
                "evidence_id": "seed",
                "kind": "doc",
                "ref": "seed.json",
                "result": "ok",
            }
        ],
        "approval_boundaries": {
            "sdk_installation_allowed": False,
            "paid_api_call_allowed": False,
            "shadow_or_canary_allowed": False,
            "production_routing_allowed": False,
            "destructive_operation_allowed": False,
        },
    }
