"""Teste API /v1/prezentari — rutare validare + idempotenta."""

from __future__ import annotations

import os
import tempfile

import pytest
from fastapi.testclient import TestClient


@pytest.fixture()
def client(monkeypatch):
    # DB temporara izolata per test.
    tmp = tempfile.mkdtemp()
    monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "t.db"))
    from app.config import get_settings
    get_settings.cache_clear()  # reincarca settings cu noul env
    from app.main import app
    with TestClient(app) as c:
        yield c
    get_settings.cache_clear()


def _body(**over):
    prez = {
        "vin": "WVWZZZ1KZAW000123",
        "nr_inmatriculare": "B999TST",
        "data_prestatie": "2026-06-15",
        "odometru_final": "123456",
        "prestatii": [{"cod_prestatie": "OE-1"}],
    }
    prez.update(over)
    return {"rar_credentials": {"email": "x@y.ro", "password": "s"}, "prezentari": [prez], "raspuns": "complet"}


def test_prezentare_valida_queued(client):
    r = client.post("/v1/prezentari", json=_body())
    assert r.status_code == 200
    assert r.json()["results"][0]["status"] == "queued"


def test_vin_invalid_needs_data(client):
    r = client.post("/v1/prezentari", json=_body(vin="WVWZZZ1OZIQ45678"))
    assert r.status_code == 200
    sid = r.json()["results"][0]
    assert sid["status"] == "needs_data"


def test_data_viitoare_needs_data(client):
    r = client.post("/v1/prezentari", json=_body(data_prestatie="2099-01-01"))
    assert r.json()["results"][0]["status"] == "needs_data"


def test_idempotenta_dedup(client):
    b = _body()
    r1 = client.post("/v1/prezentari", json=b)
    r2 = client.post("/v1/prezentari", json=b)
    id1 = r1.json()["results"][0]["submission_id"]
    res2 = r2.json()["results"][0]
    assert res2["submission_id"] == id1
    assert res2["deduped"] is True


# --------------------------------------------------------------------------- #
# Raspuns onest: erori/nemapate/motiv pe randuri blocate                      #
# --------------------------------------------------------------------------- #

def test_needs_data_intoarce_erori(client):
    """Data in viitor -> needs_data + erori 3 niveluri (DATA_VIITOR) + motiv negol."""
    r = client.post("/v1/prezentari", json=_body(data_prestatie="2099-01-01"))
    res = r.json()["results"][0]
    assert res["status"] == "needs_data"
    assert res["nemapate"] == []
    coduri = [e["cod"] for e in res["erori"]]
    assert "DATA_VIITOR" in coduri
    assert res["erori"][0]["field"] == "data_prestatie"
    assert res["motiv"]  # rezumat uman negol


def test_vin_invalid_intoarce_erori_pe_camp(client):
    """VIN cu O/I/Q -> erori cu field='vin'."""
    r = client.post("/v1/prezentari", json=_body(vin="WVWZZZ1OZIQ45678"))
    res = r.json()["results"][0]
    assert res["status"] == "needs_data"
    fields = [e["field"] for e in res["erori"]]
    assert "vin" in fields


def test_needs_mapping_intoarce_nemapate(client):
    """Cod necunoscut in nomenclator -> needs_mapping + nemapate negol, erori gol, motiv negol."""
    r = client.post("/v1/prezentari", json=_body(prestatii=[{"cod_prestatie": "VERIFICARE NECUNOSCUTA 999"}]))
    res = r.json()["results"][0]
    assert res["status"] == "needs_mapping"
    assert res["erori"] == []
    assert res["nemapate"]
    assert res["nemapate"][0]["cod_op_service"] == "VERIFICARE NECUNOSCUTA 999"
    assert res["nemapate"][0]["cod"] == "COD_NEMAPAT"
    assert res["motiv"]


def test_queued_fara_erori_nemapate_motiv(client):
    """Prezentare valida -> queued cu erori/nemapate goale si motiv null."""
    r = client.post("/v1/prezentari", json=_body())
    res = r.json()["results"][0]
    assert res["status"] == "queued"
    assert res["erori"] == [] and res["nemapate"] == []
    assert res["motiv"] is None


def test_raspuns_nu_reflecta_parola(client):
    """Raspunsul onest nu trebuie sa contina niciodata creds RAR (echo de parola)."""
    body = _body(data_prestatie="2099-01-01")
    body["rar_credentials"] = {"email": "x@y.ro", "password": "PAROLA_SECRETA_123"}
    r = client.post("/v1/prezentari", json=body)
    assert "PAROLA_SECRETA_123" not in r.text
    assert "password" not in r.text


def test_rezultate_poarta_index_si_ecou_vehicul(client):
    """Fiecare rezultat e corelabil cu cererea: index 0-based + ecou vin/nr,
    inclusiv pe randuri blocate si pe dedup."""
    body = _body()
    prez2 = dict(body["prezentari"][0])
    prez2.update({"vin": "WAUZZZ8K9BA123456", "nr_inmatriculare": "cj45xyz",
                  "data_prestatie": "2099-01-01"})
    body["prezentari"].append(prez2)
    r = client.post("/v1/prezentari", json=body)
    res = r.json()["results"]
    assert [x["index"] for x in res] == [0, 1]
    assert res[0]["vin"] == "WVWZZZ1KZAW000123"
    assert res[1]["nr_inmatriculare"] == "CJ45XYZ"  # ecou normalizat (upper)
    assert res[1]["status"] == "needs_data"

    # Dedup: acelasi continut -> rezultatul pastreaza corelarea.
    r2 = client.post("/v1/prezentari", json=body)
    res2 = r2.json()["results"]
    assert res2[0]["deduped"] is True
    assert res2[0]["index"] == 0
    assert res2[0]["vin"] == "WVWZZZ1KZAW000123"


def test_nemapat_primeste_sugestie(client):
    """Cod nemapat cu denumire apropiata de nomenclator -> sugestie fuzzy in
    nemapate[].sugestie (complet) si in motiv (ambele forme)."""
    prestatii = [{"cod_op_service": "REV-PER", "denumire": "Revizie periodica"}]
    r = client.post("/v1/prezentari", json=_body(prestatii=prestatii))
    res = r.json()["results"][0]
    assert res["status"] == "needs_mapping"
    sug = res["nemapate"][0]["sugestie"]
    assert sug["cod_prestatie"] == "OE-3"  # seed: REVIZIE PERIODICA
    assert sug["sursa"] == "fuzzy"
    assert "sugestie: OE-3" in res["motiv"]

    # Forma minima: sugestia ramane vizibila in motiv.
    body = _body(prestatii=prestatii, vin="WAUZZZ8K9BA123456")
    del body["raspuns"]
    r2 = client.post("/v1/prezentari", json=body)
    assert "sugestie: OE-3" in r2.json()["results"][0]["motiv"]


def test_raspuns_minim_implicit(client):
    """Fara `raspuns` in cerere -> forma compacta cu chei fixe, fara campurile detaliate."""
    body = _body(prestatii=[{"cod_op_service": "REP-MOT", "denumire": "Reparatie motor"}])
    del body["raspuns"]
    r = client.post("/v1/prezentari", json=body)
    res = r.json()["results"][0]
    assert set(res) == {"index", "submission_id", "vehicul", "status", "motiv", "id_prezentare"}
    assert res["index"] == 0
    assert res["vehicul"] == "B999TST"
    assert res["status"] == "needs_mapping"
    assert "REP-MOT" in res["motiv"]

    # 'minim' explicit = acelasi lucru cu default-ul.
    body["raspuns"] = "minim"
    r2 = client.post("/v1/prezentari", json=body)
    assert set(r2.json()["results"][0]) == set(res)


def test_json_malformat_422(client):
    # Lipseste vin -> validare de shape Pydantic -> 422 (NU needs_data).
    bad = {"rar_credentials": {"email": "x", "password": "y"},
           "prezentari": [{"nr_inmatriculare": "B1", "data_prestatie": "2026-06-15",
                           "odometru_final": "1", "prestatii": [{"cod_prestatie": "OE-1"}]}]}
    r = client.post("/v1/prezentari", json=bad)
    assert r.status_code == 422
