"""Teste pentru VIN pe rand separat sub numarul de inmatriculare.

VIN-ul se afiseaza intr-un element block-level (div, stil muted) sub nr.
inmatriculare, nu inline in aceeasi celula. Testul asserteaza tipul
elementului (block), nu doar prezenta textului.
"""

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 _ins(acct: int, *, vin: str = "", nr: str = "B01TST", status: str = "queued") -> int:
    from app.db import get_connection
    conn = get_connection()
    try:
        cur = conn.execute(
            "INSERT INTO submissions (idempotency_key, account_id, status, payload_json) VALUES (?, ?, ?, ?)",
            (
                f"k-{os.urandom(5).hex()}", acct, status,
                json.dumps({
                    "vin": vin,
                    "nr_inmatriculare": nr,
                    "data_prestatie": "2026-06-20",
                    "odometru_final": "100",
                    "prestatii": [{"cod_prestatie": "R-X"}],
                }),
            ),
        )
        conn.commit()
        return cur.lastrowid  # type: ignore[return-value]
    finally:
        conn.close()


@pytest.fixture()
def client(monkeypatch):
    tmp = tempfile.mkdtemp()
    monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "layout_test.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_placuta_pe_rand_identificator_primar(client):
    """Placuta (nr. inmatriculare) e identificatorul primar, linia 1 a randului slim,
    randata intr-un <div class="slim-vin"> (block-level, prominent).

    Operatorul scaneaza placuta de pe comanda, nu VIN-ul de 17 caractere —
    placuta e linia 1, VIN integral se muta in modalul de detaliu.
    """
    acct = _create_account_user("vin_layout@test.com")
    _ins(acct, vin="WVWZZZ1JZXW000001", nr="B123XYZ")
    _login(client, "vin_layout@test.com")

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

    assert "B123XYZ" in html, "placuta (nr. inmatriculare) trebuie sa apara in lista slim"

    plac = "B123XYZ"
    found_slim_vin = re.search(
        rf'<div[^>]*class="slim-vin[^"]*"[^>]*>[^<]*{re.escape(plac)}[^<]*</div>',
        html,
    )
    assert found_slim_vin, (
        f"placuta '{plac}' trebuie sa fie in <div class=\"slim-vin\"> (linia 1 a "
        f"randului slim). HTML gasit: "
        + html[max(0, html.find(plac) - 80):html.find(plac) + 80]
    )

    assert "000001" not in html, "VIN-ul nu mai trebuie randat pe randul slim"


def test_placuta_lipsa_nu_genereaza_rand_gol(client):
    """Cand placuta SI VIN-ul lipsesc, slim-vin nu afiseaza '—' izolat ca identificator.

    Fallback: VIN scurt daca exista, altfel mesaj neutru ('fara numar') — niciodata
    un em-dash singur ca identificator primar.
    """
    acct = _create_account_user("vin_gol@test.com")
    sid1 = _ins(acct, vin="", nr="B999TST")
    sid2 = _ins(acct, vin="", nr="")
    _login(client, "vin_gol@test.com")

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

    assert f'id="trimitere-row-{sid1}"' in html
    assert f'id="trimitere-row-{sid2}"' in html

    assert "B999TST" in html, "placuta (nr. inmatriculare) lipseste de pe rand"

    for m in re.finditer(r'<div[^>]*class="slim-vin[^"]*"[^>]*>([^<]*)</div>', html):
        assert m.group(1).strip() != "—", "slim-vin afiseaza '—' izolat ca identificator"

    assert "fara numar" in html, "fallback 'fara numar' lipseste cand placuta+VIN absente"


# --------------------------------------------------------------------------- #
# Tabel compact desktop (PRD 5.22): header coloane, bulina status, T/P,       #
# badge +N multi-cod, sub-linie eroare bruta.                                  #
# --------------------------------------------------------------------------- #

def _ins_full(acct: int, *, payload: dict, status: str = "queued",
              rar_env: str = "test", rar_error: str | None = None) -> int:
    from app.db import get_connection
    conn = get_connection()
    try:
        cur = conn.execute(
            "INSERT INTO submissions (idempotency_key, account_id, status, payload_json, rar_env, rar_error) "
            "VALUES (?, ?, ?, ?, ?, ?)",
            (f"k-{os.urandom(5).hex()}", acct, status,
             json.dumps(payload), rar_env, rar_error),
        )
        conn.commit()
        return int(cur.lastrowid)
    finally:
        conn.close()


def _payload_min(coduri: list[str] | None = None) -> dict:
    return {
        "vin": "WVWZZZ1JZXW000002",
        "nr_inmatriculare": "B22TST",
        "data_prestatie": "2026-06-21",
        "odometru_final": "200",
        "prestatii": [{"cod_prestatie": c} for c in (coduri or ["R-X"])],
    }


def test_desktop_header_coloane(client):
    """Lista are un rand de header cu numele coloanelor (Status, Mediu etc.)."""
    acct = _create_account_user("head.col@test.com")
    _ins(acct, nr="B77HDR")
    _login(client, "head.col@test.com")

    html = client.get("/_fragments/submissions").text
    assert "trimiteri-head" in html, "Randul de header lipseste"
    for col in ("Vehicul", "Cod RAR", "Operatie", "Status", "Mediu"):
        assert col in html, f"Coloana '{col}' lipseste din header"


def test_status_bulina_cu_tooltip(client):
    """Statusul e o bulina colorata (dot-stare) cu numele starii in title."""
    acct = _create_account_user("dot.status@test.com")
    _ins_full(acct, payload=_payload_min(), status="sent")
    _login(client, "dot.status@test.com")

    html = client.get("/_fragments/submissions").text
    m = re.search(r'<span[^>]*class="dot-stare[^"]*s-sent[^"]*"[^>]*title="([^"]+)"', html) or \
        re.search(r'<span[^>]*class="dot-stare[^"]*"[^>]*class[^>]*>', html)
    assert "dot-stare" in html, "Bulina de status (dot-stare) lipseste"
    assert m, f"Bulina fara title (tooltip cu starea): {html[html.find('dot-stare')-100:html.find('dot-stare')+200]}"


def test_mediu_litera_t_p(client):
    """Mediul RAR e litera compacta: T (testare, contur) / P (productie, fill)."""
    acct = _create_account_user("env.litera@test.com")
    _ins_full(acct, payload=_payload_min(), rar_env="test")
    _ins_full(acct, payload=_payload_min(), rar_env="prod")
    _login(client, "env.litera@test.com")

    html = client.get("/_fragments/submissions").text
    assert re.search(r'class="env-l env-l-test"[^>]*>\s*T\s*<', html), "Litera T (testare) lipseste"
    assert re.search(r'class="env-l env-l-prod"[^>]*>\s*P\s*<', html), "Litera P (productie) lipseste"


def test_multicod_badge_plus_n(client):
    """Mai multe coduri RAR: primul cod + badge +N cu toate codurile in title."""
    acct = _create_account_user("multicod@test.com")
    _ins_full(acct, payload=_payload_min(["OE-1", "OE-2", "OE-8"]))
    _ins_full(acct, payload=_payload_min(["OE-4"]))
    _login(client, "multicod@test.com")

    html = client.get("/_fragments/submissions").text
    m = re.search(r'<span class="cod-plus" title="([^"]+)">\+2</span>', html)
    assert m, "Badge-ul +2 lipseste pentru trimiterea cu 3 coduri"
    for cod in ("OE-1", "OE-2", "OE-8"):
        assert cod in m.group(1), f"Codul {cod} lipseste din tooltip-ul badge-ului"
    # un singur cod -> fara badge
    assert not re.search(r'OE-4[^<]*</span><span class="cod-plus"', html)


def test_sublinie_eroare_bruta_doar_pe_error(client):
    """Sub-linia rosie contine textul brut al erorii RAR, doar pe error/needs_data."""
    acct = _create_account_user("err.brut@test.com")
    _ins_full(
        acct, payload=_payload_min(), status="error",
        rar_error=json.dumps({
            "cod": "RAR_EROARE_SERVER",
            "problema": "RAR a esuat la inregistrarea prezentarii",
            "cauza": "ORA-12899: value too large for column PRESTATII.COD",
            "fix": "x", "field": None,
            "message": "ORA-12899: value too large for column PRESTATII.COD",
        }),
    )
    _ins_full(
        acct,
        payload={**_payload_min(), "prestatii": [{"cod_op_service": "IGIENIZARE", "denumire": "Igienizare AC"}]},
        status="needs_mapping",
        rar_error=json.dumps({"unmapped": [{"cod_op_service": "IGIENIZARE"}]}),
    )
    _login(client, "err.brut@test.com")

    html = client.get("/_fragments/submissions").text
    err_cells = re.findall(r'class="c-err"[^>]*>([^<]*)<', html)
    assert len(err_cells) == 1, f"Exact o sub-linie de eroare asteptata, gasite {len(err_cells)}"
    assert "ORA-12899" in err_cells[0], f"Textul brut RAR lipseste: {err_cells[0]!r}"


def test_mobil_pastreaza_doua_linii_cu_bulina_si_litera(client):
    """CSS-ul mobil: header ascuns, rand pe 2 linii prin grid-areas (veh / meta),
    cu actiune + mediu + status in dreapta."""
    _create_account_user("mobil.css@test.com")
    _login(client, "mobil.css@test.com")

    html = client.get("/?tab=coada").text
    assert re.search(r'\.trimiteri-head\s*\{\s*display\s*:\s*none', html), \
        "Headerul de coloane nu e ascuns pe mobil"
    m = re.search(r'grid-template-areas\s*:\s*"check id\s+veh\s+act env status"\s*"check meta meta act env status"', html)
    assert m, "Grid-areas pe 2 linii (id+veh/meta) lipseste din CSS-ul mobil"
