"""
Incident list endpoint pure-read regression tests.

目的:
- GET /api/v1/incidents 是前端輪詢與 AwoooP Console 的列表路徑。
- 預設不得因為缺少 decision token 就背景啟動 LLM / Ollama / OpenClaw。
"""

from datetime import UTC, datetime

import pytest

from src.api.v1 import incidents as incidents_api
from src.models.incident import Incident, Severity


class _IncidentService:
    async def get_active_incidents(self) -> list[Incident]:
        return [
            Incident(
                incident_id="INC-20260506-PURE01",
                severity=Severity.P2,
                affected_services=["awoooi-api"],
                created_at=datetime(2026, 5, 6, 12, 0, tzinfo=UTC),
                updated_at=datetime(2026, 5, 6, 12, 1, tzinfo=UTC),
            )
        ]


class _DecisionManager:
    def __init__(self) -> None:
        self.created = 0
        self.single_token_lookups = 0
        self.batch_token_lookups = 0

    async def _find_existing_tokens_for_incidents(self, incident_ids: list[str]):
        self.batch_token_lookups += 1
        return {}

    async def _find_existing_token(self, incident_id: str):
        self.single_token_lookups += 1
        return None

    async def get_or_create_decision(self, *args, **kwargs):
        self.created += 1
        raise AssertionError("GET /incidents must not create AI decisions by default")


@pytest.mark.asyncio
async def test_list_incidents_does_not_trigger_ai_decision_by_default(monkeypatch):
    decision_manager = _DecisionManager()
    monkeypatch.setattr(incidents_api, "get_incident_service", lambda: _IncidentService())
    monkeypatch.setattr(incidents_api, "get_decision_manager", lambda: decision_manager)

    result = await incidents_api.list_incidents(generate_missing_decisions=False)

    assert result.count == 1
    assert result.incidents[0].incident_id == "INC-20260506-PURE01"
    assert result.incidents[0].decision is None
    assert decision_manager.created == 0
    assert decision_manager.batch_token_lookups == 1
    assert decision_manager.single_token_lookups == 0
