"""Teste US-004 (PRD 3.5): "Coada" -> "Trimiteri" tabel lizibil + detaliu la click.

Coloane umane (RO), stare via labels (nu "sent" brut), vehicul/operatie/data din
payload, motiv uman. Detaliu scoped pe cont (404 cross-account).
"""

from __future__ import annotations

import json
import os
import re
import tempfile

import pytest
from starlette.testclient import TestClient


def _create_account_user(email: str, name: str = "Service", password: str = "parolasecreta10"):
    from app.accounts import create_account
    from app.users import create_user
    from app.db import get_connection

    conn = get_connection()
    try:
        acct_id = create_account(conn, name, active=True)
        create_user(conn, acct_id, email, password)
        return acct_id
    finally:
        conn.close()


def _login(client, email: str, password: str = "parolasecreta10") -> None:
    resp = client.get("/login")
    m = re.search(r'name="csrf_token"\s+value="([^"]+)"', resp.text) or \
        re.search(r'value="([^"]+)"\s+name="csrf_token"', resp.text)
    assert m
    resp = client.post("/login", data={"email": email, "parola": password, "csrf_token": m.group(1)})
    assert resp.status_code == 303


def _insert_submission(acct: int, status: str = "sent", *, payload: dict | None = None,
                       rar_error: str | None = None, id_prezentare=None) -> int:
    from app.db import get_connection
    conn = get_connection()
    try:
        p = payload if payload is not None else {
            "vin": "WVWZZZ1JZXW000777",
            "nr_inmatriculare": "B777ZZZ",
            "data_prestatie": "2026-06-18",
            "odometru_final": "55000",
            "prestatii": [{"cod_prestatie": "R-FRANE", "denumire": "Reparatie frane"}],
        }
        cur = conn.execute(
            "INSERT INTO submissions (idempotency_key, account_id, status, payload_json, rar_error, id_prezentare) "
            "VALUES (?, ?, ?, ?, ?, ?)",
            (f"k-{status}-{os.urandom(4).hex()}", acct, status, json.dumps(p), rar_error, id_prezentare),
        )
        conn.commit()
        return int(cur.lastrowid)
    finally:
        conn.close()


@pytest.fixture()
def client(monkeypatch):
    tmp = tempfile.mkdtemp()
    monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "subm.db"))
    monkeypatch.setenv("AUTOPASS_WEB_AUTH_REQUIRED", "true")
    from app.config import get_settings
    get_settings.cache_clear()
    from app.web import ratelimit
    ratelimit._hits.clear()
    from app.main import app
    with TestClient(app, follow_redirects=False) as c:
        yield c
    ratelimit._hits.clear()
    get_settings.cache_clear()


def test_submissions_coloane_umane(client):
    """US-004 (PRD 5.15): layout slim — informatia umana vizibila, cod brut ascuns.
    Anterior (pana la US-004): tabel cu antete <th>; dupa US-004: lista slim.
    Informatia ramane accesibila: vehicul/operatie din payload, stare umana,
    nr. prezentare RAR pe linia meta discreta.
    """
    acct = _create_account_user("col@test.com")
    _insert_submission(acct, "sent", id_prezentare=68516)
    _login(client, "col@test.com")

    resp = client.get("/_fragments/submissions")
    assert resp.status_code == 200
    html = resp.text

    # Layout slim prezent (US-004 PRD 5.15)
    assert "lista-trimiteri-slim" in html, "lista slim lipseste"
    assert "trimitere-slim" in html, "rand slim lipseste"

    # "HTTP RAR" NU e antet / eticheta vizibila
    assert "<th>HTTP RAR</th>" not in html
    assert "HTTP RAR" not in html

    # Starea afisata e text uman, nu 'sent' brut
    assert ">sent<" not in html, "Starea bruta 'sent' nu ar trebui afisata direct"
    assert "Declarate la RAR" in html, "Starea umana (titlu pill) lipseste"

    # Vehicul + operatie din payload vizibile pe rand slim
    assert "B777ZZZ" in html, "Nr inmatriculare din payload lipseste"
    assert "Reparatie frane" in html, "Operatia din payload lipseste"

    # 5.16: #id_prezentare nu mai e pe rand (randul are MAX 2 linii) — detaliul complet
    # (inclusiv nr. prezentare RAR) traieste in modalul de detaliu.
    assert "68516" not in html, "Nr. prezentare RAR nu trebuie sa mai apara pe randul slim"


def test_tab_eticheta_trimiteri(client):
    """US-003 (3.6): tab-ul 'Trimiteri' a fost eliminat; deep-link ?tab=coada ramane
    valid (nu 404) si serveste continutul Acasa."""
    _create_account_user("et@test.com")
    _login(client, "et@test.com")
    resp = client.get("/?tab=coada")
    assert resp.status_code == 200
    # Trimiterile traiesc acum pe Acasa, nu pe un tab separat.
    assert 'id="tab-coada"' not in resp.text
    assert 'id="acasa-section"' in resp.text or 'id="import-section"' in resp.text


def test_motiv_needs_data_afisat(client):
    """Pentru needs_data, motivul apare in detaliu (PRD 5.8 US-007: Motiv a iesit din tabel)."""
    acct = _create_account_user("motiv@test.com")
    sid = _insert_submission(
        acct, "needs_data",
        rar_error=json.dumps([{"field": "odometru_final", "message": "lipsa odometru"}]),
    )
    _login(client, "motiv@test.com")
    resp = client.get(f"/_fragments/trimitere/{sid}")
    assert resp.status_code == 200
    assert "lipsa odometru" in resp.text


def test_tabel_nu_are_coloana_motiv(client):
    """PRD 5.8 US-007: Motiv nu e o coloana separata in thead/tbody.

    Nota (PRD 5.9 US-002, R1): eticheta umana scurta a problemei apare acum sub pill-ul
    de Stare ca text mic (NU intr-o coloana proprie) — vezi test_eticheta_umana_apare_sub_pill.
    """
    acct = _create_account_user("nomotiv@test.com")
    _insert_submission(
        acct, "needs_data",
        rar_error=json.dumps([{"field": "odometru_final", "message": "lipsa odometru xyz"}]),
    )
    _login(client, "nomotiv@test.com")
    resp = client.get("/_fragments/submissions")
    assert resp.status_code == 200
    html = resp.text
    assert "<th>Motiv</th>" not in html
    # Motiv nu are coloana/celula dedicata (label-ul scurt sta sub pill in col-stare)
    assert 'data-eticheta="Motiv"' not in html


def test_operatie_contine_cod_rar(client):
    """PRD 5.9 US-002: coloana Operatie arata codul RAR simplu (FARA prefix) cand mapat, 'nemapat' cand nu."""
    acct = _create_account_user("codrar@test.com")
    # mapat: are cod_prestatie -> cod RAR vizibil
    _insert_submission(acct, "sent", payload={
        "vin": "WVWZZZ1JZXW000111",
        "nr_inmatriculare": "B111AAA",
        "data_prestatie": "2026-06-18",
        "odometru_final": "10000",
        "prestatii": [{"cod_prestatie": "OE-2", "denumire": "Verificare X"}],
    })
    # nemapat: doar cod_op_service -> "nemapat"
    _insert_submission(acct, "needs_mapping", payload={
        "vin": "WVWZZZ1JZXW000222",
        "nr_inmatriculare": "B222BBB",
        "data_prestatie": "2026-06-18",
        "odometru_final": "20000",
        "prestatii": [{"cod_op_service": "INTERN9", "denumire": "Spalare auto"}],
    })
    _login(client, "codrar@test.com")
    resp = client.get("/_fragments/submissions")
    assert resp.status_code == 200
    html = resp.text
    # US-002: codul ramane, dar prefixul textual "cod RAR:" a fost eliminat (R8)
    assert "OE-2" in html
    assert "cod RAR:" not in html
    assert "nemapat" in html


def test_pill_eticheta_scurta(client):
    """PRD 5.8 US-007/US-006: pill-ul de Stare foloseste eticheta scurta; textul lung in title."""
    acct = _create_account_user("pill@test.com")
    _insert_submission(acct, "sent", id_prezentare=70001)
    _login(client, "pill@test.com")
    resp = client.get("/_fragments/submissions")
    assert resp.status_code == 200
    html = resp.text
    # eticheta scurta in pill
    assert ">Finalizat<" in html
    # textul lung pastrat ca tooltip (title)
    assert 'title="Declarate la RAR' in html


def test_detaliu_trimitere(client):
    """/_fragments/trimitere/{id} intoarce detaliul complet scoped pe cont."""
    acct = _create_account_user("det@test.com")
    sid = _insert_submission(acct, "sent", id_prezentare=99001)
    _login(client, "det@test.com")

    resp = client.get(f"/_fragments/trimitere/{sid}")
    assert resp.status_code == 200
    html = resp.text
    assert f"Detaliu trimitere #{sid}" in html
    assert "WVWZZZ1JZXW000777" in html  # VIN integral in detaliu
    assert "99001" in html  # nr prezentare RAR


# ---------------------------------------------------------------------------
# US-002 (PRD 5.9): tabel trimiteri — eticheta umana sub pill, fara chevron,
# cod RAR simplu (fara prefix), randul declanseaza modalul. Teste de randare.
# ---------------------------------------------------------------------------

def test_eticheta_umana_apare_sub_pill(client):
    """Sub pill-ul de Stare apare eticheta umana scurta (text), nu codul brut."""
    acct = _create_account_user("ets@test.com")
    _insert_submission(
        acct, "needs_data",
        rar_error=json.dumps([{"field": "odometru_final", "message": "lipsa odometru"}]),
    )
    _login(client, "ets@test.com")
    resp = client.get("/_fragments/submissions")
    assert resp.status_code == 200
    html = resp.text
    assert "eticheta-problema" in html       # containerul textului uman sub pill
    assert "s-error" in html                 # colorat ca problema (error/needs_*)
    # NU randeaza cod brut de catalog pe rand
    assert "COD_" not in html
    assert "RAR_EROARE" not in html


def test_eticheta_umana_absenta_pe_rand_ok(client):
    """Pe randuri fara problema (sent) nu apare eticheta-problema (string gol -> nimic)."""
    acct = _create_account_user("etok@test.com")
    _insert_submission(acct, "sent", id_prezentare=70123)
    _login(client, "etok@test.com")
    resp = client.get("/_fragments/submissions")
    assert resp.status_code == 200
    assert "eticheta-problema" not in resp.text


def test_fara_chevron_in_rand(client):
    """R8: niciun chevron in coloana # / pe rand (eliminat impreuna cu CSS/JS asociat)."""
    acct = _create_account_user("chev@test.com")
    _insert_submission(acct, "sent")
    _login(client, "chev@test.com")
    resp = client.get("/_fragments/submissions")
    assert resp.status_code == 200
    assert "chevron" not in resp.text


def test_cod_rar_fara_prefix_text(client):
    """Coloana Operatie linia 2: doar codul RAR (ex. OE-2), FARA prefixul 'cod RAR:'."""
    acct = _create_account_user("crp@test.com")
    _insert_submission(acct, "sent", payload={
        "vin": "WVWZZZ1JZXW000111",
        "nr_inmatriculare": "B111AAA",
        "data_prestatie": "2026-06-18",
        "odometru_final": "10000",
        "prestatii": [{"cod_prestatie": "OE-2", "denumire": "Verificare X"}],
    })
    _login(client, "crp@test.com")
    resp = client.get("/_fragments/submissions")
    assert resp.status_code == 200
    html = resp.text
    assert "OE-2" in html                # codul ramane vizibil
    assert "cod RAR:" not in html        # prefixul textual a disparut


def test_cod_rar_nemapat_muted(client):
    """Cand nemapat, linia 2 arata 'nemapat' muted (comportament 5.8 pastrat)."""
    acct = _create_account_user("crn@test.com")
    _insert_submission(acct, "needs_mapping", payload={
        "vin": "WVWZZZ1JZXW000222",
        "nr_inmatriculare": "B222BBB",
        "data_prestatie": "2026-06-18",
        "odometru_final": "20000",
        "prestatii": [{"cod_op_service": "INTERN9", "denumire": "Spalare auto"}],
    })
    _login(client, "crn@test.com")
    resp = client.get("/_fragments/submissions")
    assert resp.status_code == 200
    assert "nemapat" in resp.text


def test_rand_deschide_modal(client):
    """Randul tinteste corpul modalului (#detaliu-modal-body), NU un rand-sibling (US-003)."""
    acct = _create_account_user("mod@test.com")
    sid = _insert_submission(acct, "sent")
    _login(client, "mod@test.com")
    resp = client.get("/_fragments/submissions")
    assert resp.status_code == 200
    html = resp.text
    assert f'hx-get="/_fragments/trimitere/{sid}"' in html
    assert 'hx-target="#detaliu-modal-body"' in html
    # randul-sibling de detaliu din 5.8 a fost eliminat
    assert "detaliu-rand" not in html


def test_rand_a11y_si_keyboard_markup(client):
    """R8 a11y: rand role=button, tabindex=0, aria-haspopup=dialog, FARA aria-expanded.

    Limitare: deschiderea efectiva pe Enter/Space si readucerea focusului pe Esc sunt
    gestionate de JS in base.html (keydown delegat), netestabile in TestClient (fara DOM).
    Verificam markup-ul/atributele care le activeaza + prezenta handler-elor de tastatura.
    """
    acct = _create_account_user("kbd@test.com")
    _insert_submission(acct, "sent")
    _login(client, "kbd@test.com")
    resp = client.get("/_fragments/submissions")
    assert resp.status_code == 200
    html = resp.text
    assert 'role="button"' in html
    assert 'tabindex="0"' in html
    assert 'aria-haspopup="dialog"' in html
    assert "aria-expanded" not in html        # R8: nu mai e expand/collapse pe rand
    # Handler-ele de tastatura traiesc in base.html (pagina completa).
    base = client.get("/?tab=coada").text
    assert "Enter" in base and "Spacebar" in base   # Enter/Space deschid modalul
    assert "Escape" in base                          # Esc inchide + readuce focusul


# ---------------------------------------------------------------------------
# US-001 (R1): eticheta umana scurta a problemei pe randul de tabel.
# Teste pure pe _submission_row_view — randarea sub pill e US-002.
# ---------------------------------------------------------------------------

def _fake_row(status: str, *, rar_error=None, id_prezentare=None, payload=None) -> dict:
    """Rand minimal compatibil cu _submission_row_view (acces prin chei)."""
    return {
        "id": 1,
        "status": status,
        "id_prezentare": id_prezentare,
        "updated_at": "2026-06-24T10:00:00",
        "rar_error": rar_error,
        "payload_json": json.dumps(payload or {
            "vin": "WVWZZZ1JZXW000777",
            "nr_inmatriculare": "B777ZZZ",
            "data_prestatie": "2026-06-18",
            "odometru_final": "55000",
            "prestatii": [{"cod_prestatie": "OE-2", "denumire": "Revizie"}],
        }),
    }


def test_eticheta_umana_sub_pill():
    """R1: randul expune `eticheta_problema` umana, reutilizand motiv (nu un nou decoder)."""
    from app.web.routes import _submission_row_view
    v = _submission_row_view(_fake_row(
        "needs_data",
        rar_error=json.dumps([{"field": "odometru_final", "message": "lipsa odometru"}]),
    ))
    # Eticheta = text uman scurt, reutilizeaza motiv (ne-gol)
    assert v["eticheta_problema"], "eticheta_problema ar trebui ne-goala pe needs_data"
    assert v["eticheta_problema"] == v["motiv"]
    # NU expune cod brut de catalog pe rand
    assert "COD_" not in v["eticheta_problema"]
    assert "RAR_EROARE" not in v["eticheta_problema"]


def test_eticheta_problema_prezenta_pe_error():
    """Eticheta ne-goala pe error chiar fara rar_error (fallback pe eticheta_scurta)."""
    from app.web.routes import _submission_row_view
    # error cu mesaj RAR
    v_err = _submission_row_view(_fake_row(
        "error", rar_error=json.dumps({"cod": "RAR_EROARE_SERVER", "problema": "Eroare server RAR"}),
    ))
    assert v_err["eticheta_problema"] == "Eroare server RAR"
    # error fara rar_error -> fallback ne-gol (eticheta scurta)
    v_fb = _submission_row_view(_fake_row("error", rar_error=None))
    assert v_fb["eticheta_problema"] == "Eroare"


def test_eticheta_problema_prezenta_pe_needs_mapping():
    """Eticheta ne-goala pe needs_mapping (stare cu problema)."""
    from app.web.routes import _submission_row_view
    v = _submission_row_view(_fake_row(
        "needs_mapping",
        rar_error=json.dumps({"unmapped": [{"cod_op_service": "OP-9", "denumire": "X"}]}),
    ))
    assert v["eticheta_problema"]
    assert "OP-9" in v["eticheta_problema"]


def test_eticheta_problema_goala_pe_rand_ok():
    """Eticheta este sir gol pe stari fara problema (queued/sending/sent)."""
    from app.web.routes import _submission_row_view
    for status in ("queued", "sending", "sent"):
        v = _submission_row_view(_fake_row(status))
        assert v["eticheta_problema"] == "", f"{status} ar trebui sa aiba eticheta goala"


def test_eticheta_problema_defensiva_json_invalid():
    """rar_error JSON corupt pe stare cu problema -> nu ridica, eticheta ne-goala."""
    from app.web.routes import _submission_row_view
    v = _submission_row_view(_fake_row("error", rar_error="{invalid json[[["))
    assert isinstance(v["eticheta_problema"], str)
    assert v["eticheta_problema"]  # fallback garanteaza text ne-gol


def test_detaliu_trimitere_404_cross_account(client):
    """Detaliul altui cont -> 404 (fara leak)."""
    acct1 = _create_account_user("d1@test.com", name="C1")
    _create_account_user("d2@test.com", name="C2")
    sid1 = _insert_submission(acct1, "sent")

    _login(client, "d2@test.com")
    resp = client.get(f"/_fragments/trimitere/{sid1}")
    assert resp.status_code == 404
    # acelasi 404 pentru un id inexistent
    resp2 = client.get("/_fragments/trimitere/999999")
    assert resp2.status_code == 404


# ---------------------------------------------------------------------------
# US-004 (PRD 5.15): lista trimiteri rand slim
# RED (inainte de implementare): testele de mai jos ESUEAZA pe tabelul vechi.
# GREEN (dupa implementare): lista slim cu .trimitere-slim / .lista-trimiteri-slim.
# ---------------------------------------------------------------------------

def test_rand_slim_vin_operatie_pill(client):
    """5.16: fiecare rand slim are 2 linii — L1 placuta (nr. inmatriculare) in .slim-vin,
    L2 cod RAR · operatie · data in .slim-meta, plus un pill de stare cu clasa stare_css
    si eticheta stare_scurt. Lista e inconjurata de .lista-trimiteri-slim.
    """
    acct = _create_account_user("slim1@test.com")
    _insert_submission(acct, "sent", id_prezentare=80001)
    _login(client, "slim1@test.com")

    resp = client.get("/_fragments/submissions")
    assert resp.status_code == 200
    html = resp.text

    # Structura slim prezenta
    assert "lista-trimiteri-slim" in html, "lista-trimiteri-slim lipseste din raspuns"
    assert "trimitere-slim" in html, "trimitere-slim lipseste din raspuns"

    # L1: placuta (identificator primar) in clasa slim-vin
    assert "slim-vin" in html, "slim-vin lipseste — linia 1 placuta"
    assert "B777ZZZ" in html, "placuta (nr. inmatriculare) lipseste de pe rand"

    # L2: cod RAR · operatie · data (slim-meta / slim-rand2)
    assert "slim-meta" in html, "slim-meta lipseste — linia 2"
    assert "slim-rand2" in html, "slim-rand2 lipseste — linia 2 (cod RAR · operatie · data)"

    # VIN integral nu mai e pe rand (5.16) — traieste in modalul de detaliu.
    assert "000777" not in html, "VIN scurt nu mai trebuie randat pe randul slim (2 linii)"

    # Pill de stare: clasa CSS + eticheta scurta
    assert "s-sent" in html, "clasa pill s-sent lipseste"
    assert "Finalizat" in html, "eticheta scurta stare_scurt lipseste"


def test_filtre_paginare_pastrate(client):
    """US-004 lock: filtrele si paginarea raman functionale dupa redesign slim.
    Lista slim afiseaza rezultatele filtrate corect.
    """
    acct = _create_account_user("filtrepag@test.com")
    _insert_submission(acct, "sent")
    _insert_submission(acct, "needs_data")
    _login(client, "filtrepag@test.com")

    # Fara filtru: ambele randuri, layout slim
    resp = client.get("/_fragments/submissions")
    assert resp.status_code == 200
    html = resp.text
    assert "lista-trimiteri-slim" in html, "lista slim lipseste din randare nefiltered"

    # OOB f-page exista (mecanismul de paginare intact)
    assert 'id="f-page"' in html, "OOB input f-page lipseste — paginarea e rupta"

    # Filtrare dupa status=sent: contul trebuie sa arate DOAR trimis
    resp_sent = client.get("/_fragments/submissions?status=sent")
    assert resp_sent.status_code == 200
    html_sent = resp_sent.text
    assert "lista-trimiteri-slim" in html_sent, "lista slim lipseste din randare filtrata"
    # Randul needs_data dispare la filtru=sent
    assert "s-needs_data" not in html_sent, "randul needs_data apare la filtru status=sent"
    # Randul sent apare
    assert "s-sent" in html_sent, "randul sent lipseste la filtru status=sent"


def test_bulk_doar_blocate(client):
    """US-004 lock: form bulk-trimiteri exista; checkbox DOAR pe randuri gestionabile
    (needs_data/needs_mapping/error); randurile read-only (sent) nu au checkbox.
    """
    acct = _create_account_user("bulk5@test.com")
    sid_blocked = _insert_submission(acct, "needs_data")   # gestionabil -> checkbox
    _insert_submission(acct, "sent")                        # read-only -> fara checkbox
    _login(client, "bulk5@test.com")

    resp = client.get("/_fragments/submissions")
    assert resp.status_code == 200
    html = resp.text

    # Layout slim prezent
    assert "lista-trimiteri-slim" in html, "lista slim lipseste — test nu acopera US-004"

    # Form bulk exista cu actiunea corecta
    assert 'id="bulk-trimiteri"' in html, "form#bulk-trimiteri lipseste"
    assert 'hx-post="/trimiteri/sterge-bulk"' in html, "actiunea bulk-delete lipseste"

    # Checkbox prezent pe randul blocat
    assert f'name="submission_id" value="{sid_blocked}"' in html, \
        f"Checkbox lipseste pe randul blocat #{sid_blocked}"

    # Exact 1 checkbox (randul sent nu are)
    checkboxes = re.findall(r'name="submission_id"', html)
    assert len(checkboxes) == 1, \
        f"Trebuie exact 1 checkbox (doar randul blocat), gasit {len(checkboxes)}"


def test_click_deschide_detaliu(client):
    """US-004: click pe randul slim deschide /_fragments/trimitere/{id} in modalul global.
    Randul are atributele HTMX si a11y necesare (role=button, aria-haspopup=dialog).
    """
    acct = _create_account_user("clickdet@test.com")
    sid = _insert_submission(acct, "sent")
    _login(client, "clickdet@test.com")

    resp = client.get("/_fragments/submissions")
    assert resp.status_code == 200
    html = resp.text

    # Layout slim ca premisa (confirma ca testul acopera noul design)
    assert "lista-trimiteri-slim" in html, "lista slim lipseste — test nu acopera US-004"

    # Randul are hx-get catre fragmentul de detaliu
    assert f'hx-get="/_fragments/trimitere/{sid}"' in html, \
        f"hx-get spre /_fragments/trimitere/{sid} lipseste"

    # Target = corpul modalului global (neschimbat fata de implementarea anterioara)
    assert 'hx-target="#detaliu-modal-body"' in html, \
        "hx-target #detaliu-modal-body lipseste"

    # Atribute a11y: role=button, tabindex=0, aria-haspopup=dialog
    assert 'role="button"' in html, "role=button lipseste pe randul slim"
    assert 'tabindex="0"' in html, "tabindex=0 lipseste pe randul slim"
    assert 'aria-haspopup="dialog"' in html, "aria-haspopup=dialog lipseste pe randul slim"
