from __future__ import annotations

from pathlib import Path

import pytest

from official_stats import OfficialItemClient, OfficialStats, OfficialStatsParseError


class _Response:
    def __init__(self, content: bytes, content_type: str = "image/jpeg"):
        self.content = content
        self.headers = {"Content-Type": content_type}

    def raise_for_status(self):
        return None


class _Session:
    def __init__(self, response: _Response):
        self.response = response
        self.calls = []

    def get(self, url: str, timeout: float):
        self.calls.append((url, timeout))
        return self.response


def _stats(url: str) -> OfficialStats:
    return OfficialStats(
        cache_key="helmet|cap|none|traveller|normal|0|0",
        url="https://example.invalid/test_items.php/",
        category="helmet",
        prefix="none",
        base="cap",
        suffix="traveller",
        quality="Zwykły",
        upgrade=0,
        legendary=False,
        player_level=80,
        item_name="Czapka Podróżnika",
        item_category="Hełm",
        suffix_image_url=url,
    )


def test_binary_image_header_is_checked_without_bytes_casefold(tmp_path: Path):
    client = OfficialItemClient(rules=None)
    client.session = _Session(_Response(b"\xff\xd8\xff\xe0JPEG-DATA"))

    paths = client.download_images(_stats("https://example.invalid/gfx/items/suffix.jpg"), tmp_path)

    assert Path(paths["suffix"]).read_bytes().startswith(b"\xff\xd8")
    assert len(client.session.calls) == 1


def test_html_payload_is_still_rejected(tmp_path: Path):
    client = OfficialItemClient(rules=None)
    client.session = _Session(_Response(b"  <!DOCTYPE HTML><html>Error</html>", "text/html"))

    with pytest.raises(OfficialStatsParseError):
        client.download_images(_stats("https://example.invalid/gfx/items/suffix.jpg"), tmp_path)
