"""Teste US-012 (PRD 5.6): un rand `error` nu mai blocheaza retrimiterea (dedup).

La resubmit cu aceeasi cheie de continut peste un rand `error`: se RE-ACTIVEAZA
(reactivated:true + stare noua), creds-urile se actualizeaza. Peste sent/queued/
sending/needs_* ramane `deduped:true` (neschimbat).
"""

from __future__ import annotations

import os
import tempfile

import pytest
from fastapi.testclient import TestClient


@pytest.fixture()
def client(monkeypatch):
    tmp = tempfile.mkdtemp()
    monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "dedup.db"))
    monkeypatch.setenv("AUTOPASS_LOG_DIR", os.path.join(tmp, "logs"))
    monkeypatch.setenv("AUTOPASS_REQUIRE_API_KEY", "false")
    from app.config import get_settings
    get_settings.cache_clear()
    from app.main import app
    with TestClient(app) as c:
        yield c
    get_settings.cache_clear()


def _body(password="corecta", **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": password}, "prezentari": [prez]}


def _force_status(sid, status):
    from app.db import get_connection
    conn = get_connection()
    try:
        conn.execute("UPDATE submissions SET status=? WHERE id=?", (status, sid))
        conn.commit()
    finally:
        conn.close()


def _creds_enc(sid):
    from app.db import get_connection
    conn = get_connection()
    try:
        return conn.execute("SELECT rar_creds_enc FROM submissions WHERE id=?", (sid,)).fetchone()["rar_creds_enc"]
    finally:
        conn.close()


def test_resubmit_peste_error_reactiveaza(client):
    r1 = client.post("/v1/prezentari", json=_body(password="gresita"))
    sid = r1.json()["results"][0]["submission_id"]
    _force_status(sid, "error")

    r2 = client.post("/v1/prezentari", json=_body(password="corecta"))
    res = r2.json()["results"][0]
    assert res["submission_id"] == sid
    assert res["reactivated"] is True
    assert res["status"] == "queued"
    assert res.get("deduped", False) is False


def test_resubmit_actualizeaza_creds_pe_reactivare(client):
    r1 = client.post("/v1/prezentari", json=_body(password="gresita"))
    sid = r1.json()["results"][0]["submission_id"]
    enc_initial = _creds_enc(sid)
    _force_status(sid, "error")

    client.post("/v1/prezentari", json=_body(password="parolaNoua"))
    enc_dupa = _creds_enc(sid)
    assert enc_dupa is not None
    assert enc_dupa != enc_initial, "creds-urile trebuie actualizate la reactivare"
    # US-013: creds propagate in slotul per-env (rar_creds_test_enc, ancora globala=test)
    from app.db import get_connection
    from app.crypto import decrypt_creds
    conn = get_connection()
    try:
        row = conn.execute("SELECT rar_creds_test_enc FROM accounts WHERE id=1").fetchone()
    finally:
        conn.close()
    assert row["rar_creds_test_enc"] is not None
    assert decrypt_creds(row["rar_creds_test_enc"])["password"] == "parolaNoua"


def test_resubmit_peste_sent_ramane_deduped(client):
    r1 = client.post("/v1/prezentari", json=_body())
    sid = r1.json()["results"][0]["submission_id"]
    _force_status(sid, "sent")
    r2 = client.post("/v1/prezentari", json=_body())
    res = r2.json()["results"][0]
    assert res["submission_id"] == sid
    assert res["deduped"] is True
    assert res.get("reactivated", False) is False
    assert res["status"] == "sent"


def test_resubmit_peste_queued_ramane_deduped(client):
    r1 = client.post("/v1/prezentari", json=_body())
    sid = r1.json()["results"][0]["submission_id"]
    # ramane queued
    r2 = client.post("/v1/prezentari", json=_body())
    res = r2.json()["results"][0]
    assert res["submission_id"] == sid
    assert res["deduped"] is True
    assert res.get("reactivated", False) is False


def test_reactivare_pe_needs_data_expune_erori(client):
    """PRD 5.7: reactivarea unui rand error care re-clasifica needs_data trebuie sa
    expuna erori/motiv (raspuns onest), nu doar status + reactivated."""
    # rand initial valid -> queued; il fortam error
    r1 = client.post("/v1/prezentari", json=_body())
    sid = r1.json()["results"][0]["submission_id"]
    _force_status(sid, "error")
    # resubmit cu aceeasi cheie de continut DAR data in viitor -> reactivare pe needs_data
    r2 = client.post("/v1/prezentari", json=_body(data_prestatie="2099-01-01"))
    res = r2.json()["results"][0]
    # cheia de continut difera (alta data) -> NU dedup; e un rand nou. Verificam ca
    # oricum raspunsul onest e populat pentru needs_data (calea de enqueue).
    assert res["status"] == "needs_data"
    assert any(e["cod"] == "DATA_VIITOR" for e in res["erori"])
    assert res["motiv"]


def test_reactivare_acelasi_continut_pastreaza_onest(client):
    """Reactivare cu EXACT acelasi continut peste un rand error -> reactivated=True;
    daca starea noua e blocata, erori/motiv sunt populate (altfel goale pe queued)."""
    r1 = client.post("/v1/prezentari", json=_body(vin="WVWZZZ1OZIQ45678"))  # VIN invalid -> needs_data
    sid = r1.json()["results"][0]["submission_id"]
    assert r1.json()["results"][0]["status"] == "needs_data"
    _force_status(sid, "error")
    r2 = client.post("/v1/prezentari", json=_body(vin="WVWZZZ1OZIQ45678"))
    res = r2.json()["results"][0]
    assert res["submission_id"] == sid
    assert res["reactivated"] is True
    assert res["status"] == "needs_data"
    # raspuns onest la reactivare: erori populate
    assert any(e["field"] == "vin" for e in res["erori"])
    assert res["motiv"]


def test_resubmit_peste_needs_data_ramane_deduped(client):
    r1 = client.post("/v1/prezentari", json=_body())
    sid = r1.json()["results"][0]["submission_id"]
    _force_status(sid, "needs_data")
    r2 = client.post("/v1/prezentari", json=_body())
    res = r2.json()["results"][0]
    assert res["deduped"] is True
    assert res.get("reactivated", False) is False
