from __future__ import annotations

import pytest

from osm_lead_source_service.errors import InvalidConfiguration
from osm_lead_source_service.markets import (
    ENGLISH_MARKET_CODES,
    ENGLISH_MARKETS,
    get_english_market,
    parse_market_selection,
)


def test_registry_contains_all_58_sovereign_english_markets() -> None:
    assert len(ENGLISH_MARKET_CODES) == 58
    assert len(ENGLISH_MARKETS) == 58
    assert {"AU", "CA", "GB", "IE", "NZ", "SG", "US", "ZA"} <= set(ENGLISH_MARKET_CODES)


def test_all_selection_is_deterministic() -> None:
    markets = parse_market_selection("all")
    assert tuple(item.country_code for item in markets) == ENGLISH_MARKET_CODES


def test_selection_accepts_aliases_and_removes_duplicates() -> None:
    markets = parse_market_selection("USA, uk, AU,US")
    assert tuple(item.country_code for item in markets) == ("AU", "GB", "US")


def test_shared_extract_markets_have_country_bounds() -> None:
    bounded = {code for code, market in ENGLISH_MARKETS.items() if market.requires_country_filter}
    assert bounded == {"AG", "BB", "DM", "GD", "KN", "LC", "SG", "TT", "VC"}
    singapore = get_english_market("SG")
    assert singapore.source_bounds is not None
    assert singapore.source_bounds.contains(1_038_198_000, 13_520_000)
    assert not singapore.source_bounds.contains(13_520_000, 1_038_198_000)


def test_unknown_market_fails_closed() -> None:
    with pytest.raises(InvalidConfiguration, match="unsupported English-market"):
        get_english_market("DE")
    with pytest.raises(InvalidConfiguration, match="empty item"):
        parse_market_selection("AU,,NZ")
