from __future__ import annotations

import pytest

from blackout_notifier.config import Config, ConfigurationError

REQUIRED = {
    "BARGHEMAN_TOKEN": "bargheman",
    "EITAAYAR_TOKEN": "eitaayar",
    "BILL_CHAT_MAP": " 123:chat-a,456:chat-b,123:chat-c,123:chat-a ,, ",
}


@pytest.fixture(autouse=True)
def do_not_load_project_dotenv(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr("blackout_notifier.config.load_dotenv", lambda **_: None)


def test_config_parses_and_deduplicates_bill_routes(monkeypatch: pytest.MonkeyPatch) -> None:
    for name, value in REQUIRED.items():
        monkeypatch.setenv(name, value)

    config = Config.from_env()

    assert config.bill_ids == ("123", "456")
    assert dict(config.bill_chat_ids) == {
        "123": ("chat-a", "chat-c"),
        "456": ("chat-b",),
    }
    assert str(config.state_file) == "state/outages.json"
    assert config.lookahead_days == 5


def test_config_reports_all_missing_required_values(monkeypatch: pytest.MonkeyPatch) -> None:
    for name in REQUIRED:
        monkeypatch.delenv(name, raising=False)

    expected = "BARGHEMAN_TOKEN.*EITAAYAR_TOKEN.*CHAT_ID.*BILL_IDS"
    with pytest.raises(ConfigurationError, match=expected):
        Config.from_env()


def test_config_rejects_non_decimal_bill_ids(monkeypatch: pytest.MonkeyPatch) -> None:
    for name, value in REQUIRED.items():
        monkeypatch.setenv(name, value)
    monkeypatch.setenv("BILL_CHAT_MAP", "123:chat-a,761/pe9314604429:chat-b")

    with pytest.raises(ConfigurationError, match="bill IDs must be decimal"):
        Config.from_env()


def test_config_rejects_malformed_routes(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    for name, value in REQUIRED.items():
        monkeypatch.setenv(name, value)

    monkeypatch.setenv("BILL_CHAT_MAP", "123")
    with pytest.raises(ConfigurationError, match="BILL_ID:CHAT_ID"):
        Config.from_env()


def test_legacy_single_chat_configuration_is_still_supported(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    monkeypatch.setenv("BARGHEMAN_TOKEN", "bargheman")
    monkeypatch.setenv("EITAAYAR_TOKEN", "eitaayar")
    monkeypatch.setenv("CHAT_ID", "legacy-chat")
    monkeypatch.setenv("BILL_IDS", "123,456,123")
    monkeypatch.delenv("BILL_CHAT_MAP", raising=False)

    config = Config.from_env()

    assert dict(config.bill_chat_ids) == {
        "123": ("legacy-chat",),
        "456": ("legacy-chat",),
    }


def test_config_validates_numeric_ranges(monkeypatch: pytest.MonkeyPatch) -> None:
    for name, value in REQUIRED.items():
        monkeypatch.setenv(name, value)
    monkeypatch.setenv("LOOKAHEAD_DAYS", "0")

    with pytest.raises(ConfigurationError, match="between 1 and 30"):
        Config.from_env()
