# tests/test_address_to_uprn_csv.py

import csv
import time
import pytest
from pathlib import Path
from backend.address2UPRN.main import get_uprn

FIXTURE_PATH = Path(__file__).parent / "test_data.csv"

# Delay between live EPC API calls to stay under the (undocumented) rate limit.
# Each parametrized case fires at least one EPC request; without throttling,
# GitHub-hosted runners burst fast enough to hit 429s.
EPC_THROTTLE_SECONDS = 1.0


@pytest.fixture(autouse=True)
def _throttle_epc_requests():
    yield
    time.sleep(EPC_THROTTLE_SECONDS)


def load_test_cases():
    with open(FIXTURE_PATH, newline="", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        return [
            pytest.param(
                row["User Input"],
                row["Postcode"],
                row["Manual UPRN Code"],
                id=f'{row["User Input"]} [{row["Postcode"]}]',
            )
            for row in reader
        ]


@pytest.mark.parametrize(
    "user_input,postcode,expected_uprn",
    load_test_cases(),
)
def test_uprn_resolution_matches_manual(
    user_input: str,
    postcode: str,
    expected_uprn: str,
):
    from utils.logger import setup_logger

    uprn = get_uprn(user_input, postcode)
    if uprn:
        assert uprn == expected_uprn
    else:
        assert str(uprn) == expected_uprn
