"""Teste US-008 (PRD 5.10): simplificare erori in formularul de editare.

Problema actuala: cardul erori_3n/card_erori (clasa eroare-3n) e randat INAINTE de form,
in afara ramurii `{% if editabil %}` — deci apare si in contextul de editare.

US-008 cere:
- In editare: cardul 3-niveluri (`eroare-3n`) DISPARUT; erori per-camp raman ca text simplu
  subliniat (.s-error); erori fara camp (field None) apar ca rezumat simplu top-of-form.
- In read-only: cardul 3-niveluri se pastreaza (comportament existent).
"""

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 _csrf(client) -> str:
    resp = client.get("/")
    m = re.search(r'name="csrf_token"\s+value="([^"]+)"', resp.text)
    assert m
    return m.group(1)


def _insert(acct: int, *, status: str, rar_error: str | None = None,
            vin: str = "WVWZZZ1JZXW000099", nr: str = "B100TST") -> int:
    from app.db import get_connection
    conn = get_connection()
    try:
        payload = json.dumps({
            "vin": vin,
            "nr_inmatriculare": nr,
            "data_prestatie": "2026-06-20",
            "odometru_final": "50000",
            "prestatii": [{"cod_prestatie": "OE-1"}],
        })
        cur = conn.execute(
            "INSERT INTO submissions "
            "(idempotency_key, account_id, status, payload_json, rar_error) "
            "VALUES (?, ?, ?, ?, ?)",
            (f"k-{os.urandom(6).hex()}", acct, status, payload, rar_error),
        )
        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, "eroare_simpla.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_form_editare_fara_card_3niveluri(client):
    """In contextul editabil (needs_data), cardul erori_3n (eroare-3n) NU apare.

    Problema curenta: cardul e randat INAINTE de form, in afara ramurii editabil,
    deci apare atat in editare cat si read-only. US-008 il muta in `{% if not editabil %}`.
    """
    acct = _create_account_user("edit3n@test.com")
    # needs_data cu rar_error care contine o eroare cu field — format {field, message}
    rar_error = json.dumps([
        {"field": "odometruFinal", "message": "Odometru trebuie sa fie un numar intreg (ca string)."}
    ])
    sid = _insert(acct, status="needs_data", rar_error=rar_error)
    _login(client, "edit3n@test.com")

    resp = client.get(f"/_fragments/trimitere/{sid}")
    assert resp.status_code == 200
    html = resp.text

    # In editare: cardul cu 3 niveluri NU trebuie sa apara
    assert 'class="eroare-3n"' not in html, (
        "Cardul erori_3n (eroare-3n) NU trebuie sa apara in contextul editabil (needs_data). "
        "US-008: muta-l in '{% if not editabil %}'."
    )
    assert 'eroare-3n-item' not in html, (
        "Itemii card-ului 3n (eroare-3n-item) nu trebuie sa apara in editare."
    )
    # Formularul de editare trebuie sa ramana prezent
    assert 'hx-post=' in html and 'corecteaza' in html, "Formularul de corectie trebuie sa existe"


def test_eroare_pe_camp_doar_text_simplu(client):
    """Dupa o corectie invalida, eroarea per-camp apare ca .s-error text simplu, nu card 3n.

    Macro-ul `camp` deja printeaza doar mesajul simplu — testul verifica ca
    `eroare-3n` nu exista in raspuns (nu e dobla-randat odata prin card si odata prin macro).
    """
    acct = _create_account_user("simplu@test.com")
    sid = _insert(acct, status="needs_data", vin="WVWZZZ1JZXW000001", nr="B100TST")
    _login(client, "simplu@test.com")
    csrf = _csrf(client)

    # POST cu odometru invalid (non-numeric) — ramane needs_data + eroare per-camp
    resp = client.post(
        f"/trimitere/{sid}/corecteaza",
        data={
            "nr_inmatriculare": "B100TST",
            "vin": "WVWZZZ1JZXW000001",
            "data_prestatie": "2026-06-20",
            "odometru_final": "nu-e-numar",
            "csrf_token": csrf,
        },
    )
    assert resp.status_code == 200
    html = resp.text

    # Eroarea per-camp trebuie sa apara ca text simplu (.s-error)
    assert 's-error' in html, "Eroarea per-camp trebuie sa apara ca .s-error text simplu"

    # Cardul 3-niveluri NU trebuie sa apara in contextul editabil
    assert 'class="eroare-3n"' not in html, (
        "Cardul eroare-3n NU trebuie sa apara in contextul editabil. "
        "US-008: randat doar in read-only ({% if not editabil %})."
    )


def test_eroare_fara_camp_apare_ca_rezumat_in_editare(client):
    """Erori cu field=None nu dispar silentios in editare — apar ca rezumat simplu top-of-form.

    Bug M6: template-ul filtra erorile in `err_map` DOAR pe cele cu field,
    iar cardul 3n (ascuns in editare) era singurul canal de afisare pentru field=None.
    US-008: adauga un rezumat simplu (div .s-error sau similar) in ramura editabil.
    """
    acct = _create_account_user("faracam@test.com")
    # rar_error cu o eroare FARA camp (field=None) — ex. eroare globala de la RAR
    rar_error = json.dumps([
        {"problema": "Date incomplete la nivel de prezentare", "cauza": "", "fix": "", "field": None}
    ])
    sid = _insert(acct, status="needs_data", rar_error=rar_error)
    _login(client, "faracam@test.com")

    resp = client.get(f"/_fragments/trimitere/{sid}")
    assert resp.status_code == 200
    html = resp.text

    # Mesajul erorii globale trebuie sa fie prezent (nu silentios disparut)
    assert "Date incomplete la nivel de prezentare" in html, (
        "Eroarea fara camp (field=None) trebuie sa apara in contextul editabil. "
        "US-008 (M6): adauga rezumat simplu top-of-form in ramura '{% if editabil %}'."
    )
    # Dar NU ca card 3-niveluri
    assert 'class="eroare-3n"' not in html, (
        "Cardul eroare-3n NU trebuie sa apara in contextul editabil."
    )


def test_readonly_pastreaza_card_3niveluri(client):
    """In contextul read-only (error/sent), cardul erori_3n se pastreaza neschimbat."""
    acct = _create_account_user("readonly3n@test.com")
    rar_error = json.dumps([
        {"problema": "Eroare RAR server", "cauza": "ORA-12899", "fix": "Reverifica datele", "field": None}
    ])
    sid = _insert(acct, status="error", rar_error=rar_error)
    _login(client, "readonly3n@test.com")

    resp = client.get(f"/_fragments/trimitere/{sid}")
    assert resp.status_code == 200
    html = resp.text

    # In read-only: cardul eroare-3n TREBUIE sa apara
    assert 'class="eroare-3n"' in html, (
        "Cardul erori_3n (eroare-3n) trebuie pastrat in contextul read-only (error)."
    )
