"""Teste PRD 5.5 — uniformizare UI: US-001 (Acasa fara Ajutor), US-002 (Nomenclator grila
standard), US-003 (macro autosend) — actualizat dupa PRD 5.11 US-002 (macro neutralizat).
"""

from __future__ import annotations

import os
import re
import tempfile
from pathlib import Path

import pytest
from jinja2 import Environment, FileSystemLoader
from starlette.testclient import TestClient

_TEMPLATES = Path(__file__).resolve().parents[1] / "app" / "web" / "templates"


def _env():
    return Environment(loader=FileSystemLoader(str(_TEMPLATES)), autoescape=True)


# ============================================================
# US-002: Nomenclator ca tabel standard (grila Trimiteri)
# ============================================================

def test_nomenclator_grila_standard_cu_randuri():
    tmpl = _env().get_template("_nomenclator.html")
    html = tmpl.render(rows=[
        {"cod_prestatie": "A012", "nume_prestatie": "Revizie tehnica", "updated_at": "2026-06-20"},
    ])
    assert "tablewrap" in html
    assert "<table" in html
    assert 'class="pill"' in html  # codul in pill, ca la Trimiteri
    assert "A012" in html and "Revizie tehnica" in html


def test_nomenclator_empty_state():
    tmpl = _env().get_template("_nomenclator.html")
    html = tmpl.render(rows=[])
    assert 'class="empty"' in html
    assert "Nomenclator gol" in html


# ============================================================
# US-003: macro autosend_toggle compact (Auto/Manual)
# ============================================================

def _render_macro(form_id="map-1", checked=True):
    mod = _env().get_template("_macros.html").module
    return str(mod.autosend_toggle(form_id=form_id, checked=checked))


def test_autosend_pastreaza_name_si_prezenta():
    """US-002 (PRD 5.11): macro autosend_toggle neutralizat — output gol, fara checkbox."""
    html = _render_macro(checked=True)
    assert 'name="auto_send"' not in html, "US-002: checkbox auto_send scos din macro"
    assert html.strip() == "", f"macro neutralizat trebuie sa intoarca string gol, got: {html!r}"


def test_autosend_nebifat_fara_checked():
    """US-002: macro neutralizat intoarce gol indiferent de checked."""
    html = _render_macro(checked=False)
    assert 'name="auto_send"' not in html
    assert html.strip() == ""


def test_autosend_compact_fara_proza_inline():
    """US-002: macro neutralizat nu contine nicio proza inline."""
    html = _render_macro()
    assert "La fisierele viitoare" not in html
    assert "Tine pentru verificare" not in html
    assert "nimic nu pleaca la RAR" not in html
    assert html.strip() == ""


# ============================================================
# US-001: Acasa fara sectiunea Ajutor
# ============================================================

@pytest.fixture()
def client(monkeypatch):
    tmp = tempfile.mkdtemp()
    monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "uniform_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 _login(client, email="u@test.com", password="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, "Service Test", active=True)
        create_user(conn, acct_id, email, password)
    finally:
        conn.close()
    resp = client.get("/login")
    csrf = re.search(r'name="csrf_token"\s+value="([^"]+)"', resp.text).group(1)
    resp = client.post("/login", data={"email": email, "parola": password, "csrf_token": csrf})
    assert resp.status_code == 303
    return acct_id


def test_acasa_fara_sectiune_ajutor(client):
    _login(client)
    resp = client.get("/_fragments/acasa")
    assert resp.status_code == 200
    # randul "Ajutor:" cu wayfinding Mapari/Coduri RAR eliminat din Acasa
    assert "Ajutor:" not in resp.text
    assert "Coduri RAR" not in resp.text


# ============================================================
# US-005: Tabel Mapari standardizat + panou Ajutor
# ============================================================

def _seed_needs_mapping(acct_id, cod_op="OP-NM", denumire="Operatie test"):
    import json
    from app.db import get_connection
    conn = get_connection()
    try:
        conn.execute(
            "INSERT INTO submissions (idempotency_key, account_id, status, payload_json) "
            "VALUES (?, ?, 'needs_mapping', ?)",
            (f"k-{cod_op}", acct_id,
             json.dumps({"prestatii": [{"cod_op_service": cod_op, "denumire": denumire}]})),
        )
        conn.commit()
    finally:
        conn.close()


def test_mapari_ajutor_disclosure_si_fara_proza_inline(client):
    acct = _login(client)
    _seed_needs_mapping(acct)
    resp = client.get("/_fragments/mapari")
    assert resp.status_code == 200
    html = resp.text
    # US-010: sectiunea de ajutor (<details class="ajutor-mapari">) eliminata
    assert "ajutor-mapari" not in html
    # US-002: coloana In coada scoasa din tabel
    assert "In coada" not in html, "US-002: coloana 'In coada' scoasa din tabelul Mapari"
    # proza inline veche eliminata de pe sectiuni
    assert "sugestia fuzzy e preselectata) si salveaza" not in html
    assert "Maparile operatie -> cod RAR retinute pentru contul tau" not in html


def test_mapari_comutator_compact_in_tabel(client):
    """US-002: tabul Mapari nu mai contine checkbox auto_send."""
    acct = _login(client)
    _seed_needs_mapping(acct)
    html = client.get("/_fragments/mapari").text
    assert 'name="auto_send"' not in html, "US-002: checkbox auto_send scos din UI"
