from __future__ import annotations

from typing import Any

import pytest

from l4d2web.services import steam_users


class _FakeResponse:
    def __init__(self, json_body: dict[str, Any], status: int = 200) -> None:
        self._body = json_body
        self.status_code = status

    def raise_for_status(self) -> None:
        if self.status_code >= 400:
            raise RuntimeError(f"http {self.status_code}")

    def json(self) -> dict[str, Any]:
        return self._body


def _patched_get(monkeypatch: pytest.MonkeyPatch, body: dict, capture: list) -> None:
    def fake_get(url: str, params: dict, timeout: float = 30.0) -> _FakeResponse:
        capture.append({"url": url, "params": params, "timeout": timeout})
        return _FakeResponse(body)

    monkeypatch.setattr(steam_users, "_session_get", fake_get)


def test_fetch_profiles_batch_builds_correct_request(monkeypatch: pytest.MonkeyPatch) -> None:
    captured: list = []
    body = {"response": {"players": [
        {"steamid": "76561197960828710", "personaname": "Alice",
         "avatarfull": "https://avatars.../alice_full.jpg"},
    ]}}
    _patched_get(monkeypatch, body, captured)

    profiles = steam_users.fetch_profiles_batch(
        ["76561197960828710", "76561198021234567"], api_key="KEY"
    )

    assert captured[0]["url"].endswith("/GetPlayerSummaries/v0002/")
    assert captured[0]["params"]["key"] == "KEY"
    assert captured[0]["params"]["steamids"] == "76561197960828710,76561198021234567"
    assert len(profiles) == 1
    p = profiles[0]
    assert p.steam_id_64 == "76561197960828710"
    assert p.persona_name == "Alice"
    assert p.avatar_url.endswith("alice_full.jpg")


def test_fetch_profiles_batch_skips_private_or_missing(monkeypatch: pytest.MonkeyPatch) -> None:
    # The Steam API simply omits non-resolvable IDs from the response. Caller
    # should accept that and return only what's there.
    body = {"response": {"players": [
        {"steamid": "76561197960828710", "personaname": "Alice",
         "avatarfull": "https://avatars.../alice_full.jpg"},
    ]}}
    _patched_get(monkeypatch, body, [])
    profiles = steam_users.fetch_profiles_batch(
        ["76561197960828710", "76561197999999999"], api_key="KEY"
    )
    assert len(profiles) == 1
    assert profiles[0].steam_id_64 == "76561197960828710"


def test_fetch_profiles_batch_chunks_by_100(monkeypatch: pytest.MonkeyPatch) -> None:
    ids = [str(76561197960000000 + i) for i in range(150)]
    calls: list = []
    body = {"response": {"players": []}}
    _patched_get(monkeypatch, body, calls)

    steam_users.fetch_profiles_batch(ids, api_key="KEY")

    assert len(calls) == 2
    assert calls[0]["params"]["steamids"].count(",") == 99   # 100 ids -> 99 commas
    assert calls[1]["params"]["steamids"].count(",") == 49   # 50 ids
