"""build_key incorporeaza rar_env."""

from __future__ import annotations

from app.idempotency import build_key, canonicalize_row, normalize_nr_inmatriculare


def _canon():
    raw = {
        "vin": "WVWZZZ1JZXW000001", "nr_inmatriculare": "B 123 ABC",
        "data_prestatie": "2026-01-10", "odometru_final": "123456.0",
        "prestatii": [{"cod_prestatie": "OE-1"}],
    }
    canon = canonicalize_row(raw)
    canon["prestatii"] = raw["prestatii"]
    return canon


def test_key_difera_intre_test_si_prod():
    canon = _canon()
    assert build_key(1, canon, "test") != build_key(1, canon, "prod")


def test_key_stabil_pe_env():
    canon = _canon()
    assert build_key(1, canon, "prod") == build_key(1, canon, "prod")
    # None si 1 colapseaza la aceeasi cheie (account_or_default), pe acelasi env
    assert build_key(None, canon, "test") == build_key(1, canon, "test")


def test_normalize_nr_inmatriculare_elimina_spatii_cratime_puncte():
    assert normalize_nr_inmatriculare("B 99 XYZ") == "B99XYZ"
    assert normalize_nr_inmatriculare("B-99-XYZ") == "B99XYZ"
    assert normalize_nr_inmatriculare("B.99.XYZ") == "B99XYZ"
    assert normalize_nr_inmatriculare(" b99xyz ") == "B99XYZ"


def test_canonicalize_row_normalizeaza_nr_inmatriculare():
    raw = {"nr_inmatriculare": "B 99 XYZ"}
    assert canonicalize_row(raw)["nr_inmatriculare"] == "B99XYZ"


def test_build_key_acelasi_pentru_formate_echivalente_nrinm():
    """"B 99 XYZ" si "B99XYZ" trebuie sa produca aceeasi cheie de dedup."""
    raw_cu_spatii = {
        "vin": "WVWZZZ1JZXW000001", "nr_inmatriculare": "B 99 XYZ",
        "data_prestatie": "2026-01-10", "odometru_final": "123456",
        "prestatii": [{"cod_prestatie": "OE-1"}],
    }
    raw_fara_spatii = {
        "vin": "WVWZZZ1JZXW000001", "nr_inmatriculare": "B99XYZ",
        "data_prestatie": "2026-01-10", "odometru_final": "123456",
        "prestatii": [{"cod_prestatie": "OE-1"}],
    }
    canon1 = canonicalize_row(raw_cu_spatii)
    canon1["prestatii"] = raw_cu_spatii["prestatii"]
    canon2 = canonicalize_row(raw_fara_spatii)
    canon2["prestatii"] = raw_fara_spatii["prestatii"]
    assert build_key(1, canon1, "test") == build_key(1, canon2, "test")

