"""Teste US-005 (PRD 5.10): VIN pe rand separat sub numarul de inmatriculare.

VIN-ul era randat ca <span> inline in aceeasi celula cu nr. Story-ul cere un
element block-level (div/small/p cu display:block) sub nr, in stil muted.
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
    (5.16): in <div class="slim-vin"> (block-level, prominent).

    PRD 5.15 (US-004): VIN era identificatorul primar pe linia 1.
    5.16 (directiva user): operatorul scaneaza placuta de pe comanda, nu VIN-ul de 17
    caractere — placuta devine 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

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

    # Placuta e intr-un element block-level (div cu clasa slim-vin)
    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]
    )

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


def test_placuta_lipsa_nu_genereaza_rand_gol(client):
    """Cand placuta SI VIN-ul lipsesc, slim-vin nu afiseaza '—' izolat ca identificator.
    Fallback (5.16): 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")
    # Placuta prezenta -> e identificatorul primar pe linia 1.
    sid1 = _ins(acct, vin="", nr="B999TST")
    # Placuta SI VIN absente -> fallback 'fara numar' (nu '—' izolat).
    sid2 = _ins(acct, vin="", nr="")
    _login(client, "vin_gol@test.com")

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

    # Ambele randuri exista
    assert f'id="trimitere-row-{sid1}"' in html
    assert f'id="trimitere-row-{sid2}"' in html

    # Placuta vizibila cand exista
    assert "B999TST" in html, "placuta (nr. inmatriculare) lipseste de pe rand"

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

    # Fallback neutru cand placuta + VIN lipsesc
    assert "fara numar" in html, "fallback 'fara numar' lipseste cand placuta+VIN absente"
