from __future__ import annotations

import traceback

import pytest

from osm_lead_source_service.errors import PbfDownloadRejected
from osm_lead_source_service.pbf import load_test_pbf_download_settings

_VALID = {
    "OSM_LEAD_SOURCE_PBF_DOWNLOAD_ENV": "test",
    "OSM_LEAD_SOURCE_TEST_PBF_REGION_ID": "fixture",
    "OSM_LEAD_SOURCE_TEST_PBF_URL": "http://127.0.0.1:8765/tiny.osm.pbf",
    "OSM_LEAD_SOURCE_TEST_PBF_SHA256": "a" * 64,
    "OSM_LEAD_SOURCE_TEST_PBF_SIZE_BYTES": "10",
}


def test_explicit_test_settings_load() -> None:
    settings = load_test_pbf_download_settings(_VALID)
    assert settings.region_id == "fixture"
    assert settings.expected_size_bytes == 10


def test_missing_or_wrong_environment_fails_closed() -> None:
    with pytest.raises(PbfDownloadRejected, match="must be exactly test"):
        load_test_pbf_download_settings({})
    values = dict(_VALID, OSM_LEAD_SOURCE_PBF_DOWNLOAD_ENV="production")
    with pytest.raises(PbfDownloadRejected, match="must be exactly test"):
        load_test_pbf_download_settings(values)


def test_generic_download_variables_are_ignored() -> None:
    with pytest.raises(PbfDownloadRejected):
        load_test_pbf_download_settings(
            {
                "PBF_URL": "http://127.0.0.1:8765/tiny.osm.pbf",
                "GEOFABRIK_URL": "https://download.geofabrik.de/test.osm.pbf",
                "DATABASE_URL": "postgresql://ignored",
            }
        )


@pytest.mark.parametrize(
    ("name", "value"),
    [
        ("OSM_LEAD_SOURCE_TEST_PBF_SIZE_BYTES", "ten"),
        ("OSM_LEAD_SOURCE_TEST_PBF_MAX_SIZE_BYTES", "large"),
        ("OSM_LEAD_SOURCE_TEST_PBF_TIMEOUT_SECONDS", "later"),
    ],
)
def test_numeric_errors_are_sanitized(name: str, value: str) -> None:
    values = dict(_VALID)
    values[name] = value
    with pytest.raises(PbfDownloadRejected) as caught:
        load_test_pbf_download_settings(values)
    rendered = "".join(
        traceback.format_exception(type(caught.value), caught.value, caught.value.__traceback__)
    )
    assert _VALID["OSM_LEAD_SOURCE_TEST_PBF_URL"] not in rendered
