from __future__ import annotations

import json
import tempfile
import unittest
from datetime import date, timedelta
from pathlib import Path

from hockey_data.client import Stat2TVNotFoundError, Stat2TVResponse
from hockey_data.config import HockeySettingsStore
from hockey_data.models import Tournament
from hockey_data.service import HockeyDataService
from support import LocalTestDatabase


class ManualGameDiscoveryTests(unittest.IsolatedAsyncioTestCase):
    async def test_active_tournament_without_gameid_flag_is_probed_first(self) -> None:
        with tempfile.TemporaryDirectory() as temp_dir:
            base_dir = Path(temp_dir)
            database = LocalTestDatabase(base_dir / "test.sqlite3")
            database.create_all()
            settings = HockeySettingsStore(base_dir / "settings")
            service = HockeyDataService(
                base_dir=base_dir,
                database=database,
                settings=settings,
            )

            today = date.today()
            with database.session() as session:
                session.add(
                    Tournament(
                        external_id="1437",
                        name_ru="Предсезонные матчи КХЛ",
                        season="2026-2027",
                        start_date=today - timedelta(days=10),
                        end_date=today + timedelta(days=20),
                        game_id_supported=False,
                    )
                )
                for index in range(120):
                    session.add(
                        Tournament(
                            external_id=str(1000 + index),
                            name_ru=f"Архив {index}",
                            season="2025-2026",
                            start_date=today - timedelta(days=300),
                            end_date=today - timedelta(days=200),
                            game_id_supported=True,
                        )
                    )

            calls: list[str] = []

            async def fake_fetch(endpoint: str) -> Stat2TVResponse:
                calls.append(endpoint)
                if endpoint == "1437/json/902918.json":
                    payload = {
                        "game": {
                            "idschedule": 902918,
                            "teamA": "A",
                            "teamB": "B",
                            "idclubA": 1,
                            "idclubB": 2,
                        },
                        "players": {},
                        "teams": {},
                    }
                    return Stat2TVResponse(
                        content=json.dumps(payload).encode("utf-8"),
                        status_code=200,
                        content_type="application/json",
                        auth_mode="test",
                        url=f"https://example.test/{endpoint}",
                    )
                raise Stat2TVNotFoundError(
                    f"https://example.test/{endpoint}", status_code=404
                )

            service.client.fetch_xml = fake_fetch  # type: ignore[method-assign]
            found = await service._discover_game_tournament("902918")

            self.assertEqual(found, "1437")
            self.assertEqual(calls, ["1437/json/902918.json"])
            database.engine.dispose()


if __name__ == "__main__":
    unittest.main()
