"""Teste US-003 (PRD 5.10): pill-uri de filtrare per categorie in bara de status.

Cazuri:
- pill_per_categorie_cu_numar: pill-uri <button> cu numarul corect per categorie
- pill_click_seteaza_status: pill-urile au atributele HTMX corecte (status=X, aria-pressed)
- fara_lista_id_uri: lista de ID-uri/VIN-uri nu mai apare in bara de status
"""

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, *, status: str, vin: str = "WVIN000000000001", nr: str = "B001") -> 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, "pill.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_pill_per_categorie_cu_numar(client):
    """Bara de status afiseaza pill-uri <button> cu numarul corect per categorie blocata."""
    acct = _create_account_user("pill1@test.com")
    # 2x needs_data, 1x needs_mapping, 1x error, 1x sent (fara pill)
    _ins(acct, status="needs_data",    vin="WVIN_ND1_001", nr="BND1")
    _ins(acct, status="needs_data",    vin="WVIN_ND1_002", nr="BND2")
    _ins(acct, status="needs_mapping", vin="WVIN_NM1_001", nr="BNM1")
    _ins(acct, status="error",         vin="WVIN_ER1_001", nr="BER1")
    _ins(acct, status="sent",          vin="WVIN_SE1_001", nr="BSE1")
    _login(client, "pill1@test.com")

    # Pill-urile traiesc in bara de filtre din sectiunea Trimiteri.
    resp = client.get("/?tab=acasa")
    assert resp.status_code == 200
    body = resp.text

    # Pill-urile sunt elemente <button>
    assert "<button" in body, "Pill-urile trebuie sa fie elemente <button>"

    # Fiecare categorie problemativa apare ca pill
    assert 'data-status="needs_data"' in body,    "Pill needs_data trebuie sa apara"
    assert 'data-status="needs_mapping"' in body, "Pill needs_mapping trebuie sa apara"
    assert 'data-status="error"' in body,         "Pill error trebuie sa apara"

    # Contoarele sunt afisate in pill-uri
    assert ">2<" in body or "2<" in body, "Contorul 2 pt needs_data trebuie vizibil in pill"

    # Starea 'sent' nu produce pill (nu e categorie de problema)
    assert 'data-status="sent"' not in body, "Nu trebuie pill pentru sent"


def test_pill_click_seteaza_status(client):
    """Pill-urile au atributele HTMX corecte: hx-get cu status=X si aria-pressed."""
    acct = _create_account_user("pill2@test.com")
    _ins(acct, status="needs_data",    vin="WVIN_ND2_001", nr="BND_P2a")
    _ins(acct, status="needs_mapping", vin="WVIN_NM2_001", nr="BNM_P2a")
    _ins(acct, status="error",         vin="WVIN_ER2_001", nr="BER_P2a")
    _login(client, "pill2@test.com")

    resp = client.get("/?tab=acasa")
    assert resp.status_code == 200
    body = resp.text

    # Fiecare pill scrie campul de filtru prin filtreazaStare(this, 'X')
    assert "filtreazaStare(this, 'needs_data')" in body,    "Pill needs_data trebuie sa apeleze filtreazaStare cu needs_data"
    assert "filtreazaStare(this, 'needs_mapping')" in body, "Pill needs_mapping trebuie sa apeleze filtreazaStare cu needs_mapping"
    assert "filtreazaStare(this, 'error')" in body,         "Pill error trebuie sa apeleze filtreazaStare cu error"

    # Pill-urile au aria-pressed pentru accesibilitate (WCAG)
    assert "aria-pressed" in body, "Pill-urile trebuie sa aiba atribut aria-pressed"

    # Filtrarea trece prin form-ul care targeteaza tabelul de trimiteri
    assert "submissions-wrap" in body and "_fragments/submissions" in body, (
        "Form-ul de filtre trebuie sa targeteze #submissions-wrap prin /_fragments/submissions"
    )


def test_fara_lista_id_uri(client):
    """Lista de ID-uri/VIN-uri (ex. #1 WVIN... / B...) nu mai apare in bara de status."""
    acct = _create_account_user("pill3@test.com")
    sid = _ins(acct, status="needs_data", vin="WVIN_ND3_UNIC001", nr="BND_P3")
    _login(client, "pill3@test.com")

    resp = client.get("/_fragments/status")
    assert resp.status_code == 200
    body = resp.text

    # Structura <li class="muted"> cu randuri blocate a disparut
    assert '<li class="muted"' not in body, (
        "Structura <li class='muted'> cu randuri blocate trebuie eliminata din bara de status"
    )
    # VIN-ul complet nu mai apare in bara de status (era partial, dar nici partial nu mai vrem)
    assert "WVIN_ND3_UNIC001" not in body, (
        "VIN-ul (sau partial) nu trebuie sa mai apara in bara de status"
    )


def test_pill_needs_mapping_culoare_warn(client):
    """Pill-ul 'Lipsa cod' (needs_mapping) foloseste --warn (chihlimbar), nu --err (DESIGN.md).

    DESIGN.md §Componente: 'Lipsa cod = --warn'. Celelalte categorii (needs_data, error) = --err.
    """
    acct = _create_account_user("warn@test.com")
    # Inseram DOAR needs_mapping — pentru a izola culoarea si a nu confunda cu --err
    _ins(acct, status="needs_mapping", vin="WVIN_NM_WARN0001", nr="BNMW1")
    _login(client, "warn@test.com")

    resp = client.get("/?tab=acasa")
    assert resp.status_code == 200
    body = resp.text

    # Pill-ul needs_mapping trebuie sa aiba culoarea --warn (nu --err)
    assert "var(--warn)" in body, (
        "Pill needs_mapping trebuie sa foloseasca var(--warn) conform DESIGN.md §Componente"
    )
    assert 'data-status="needs_mapping"' in body, "Pill needs_mapping trebuie sa fie prezent in bara de filtre"
