"""Teste US-011 (PRD 5.10): butoane salvare/stergere + dirty state pe Mapari.

Actualizat PRD 5.13: superseda sistemul .icon-btn din 5.10 -> sistem .act
(desktop text / mobil iconita 44px).

Cerinte:
- Butoane .act mereu vizibile pe rand (nu ascunse in kebab)
- Meniu kebab (<details class="kebab">) eliminat
- aria-label pe fiecare buton .act (label scurt: "Salveaza" / "Sterge")
- Iconita Lucide (.act-ic svg) prezenta in output
- data-dirty-form pe butonul de salvare (permite JS dirty-state)
"""

from __future__ import annotations

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 _seed_saved_mapping(acct_id: int) -> None:
    """Insereaza o mapare salvata in operations_mapping."""
    from app.db import get_connection
    conn = get_connection()
    try:
        conn.execute(
            "INSERT INTO operations_mapping (account_id, cod_op_service, cod_prestatie, auto_send) "
            "VALUES (?, ?, ?, ?)",
            (acct_id, "OP-TEST-77", "OE-1", 1),
        )
        conn.commit()
    finally:
        conn.close()


@pytest.fixture()
def client(monkeypatch):
    tmp = tempfile.mkdtemp()
    monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "mapari_actiuni.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_butoane_icon_vizibile_pe_rand_salvate(client):
    """Butoanele de salvare/stergere in 'Mapari salvate' au clasele .act (mereu vizibile pe rand).

    PRD 5.13: .icon-btn inlocuit cu sistemul .act (act-save / act-del).
    """
    acct = _create_account_user("actiuni_icon@test.com")
    _seed_saved_mapping(acct)
    _login(client, "actiuni_icon@test.com")

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

    assert 'class="act act-save"' in html, (
        "Butonul de salvare din 'Mapari salvate' trebuie sa aiba clasa 'act act-save' "
        "(mereu vizibil pe rand, nu ascuns in kebab)."
    )
    assert 'class="act act-del"' in html, (
        "Butonul de stergere din 'Mapari salvate' trebuie sa aiba clasa 'act act-del' "
        "(mereu vizibil pe rand, nu ascuns in kebab)."
    )


def test_fara_kebab_meniu(client):
    """Meniul kebab (details.kebab / kebab-menu) e eliminat din 'Mapari salvate'."""
    acct = _create_account_user("actiuni_kebab@test.com")
    _seed_saved_mapping(acct)
    _login(client, "actiuni_kebab@test.com")

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

    assert 'class="kebab"' not in html, (
        "Meniul kebab (details.kebab) trebuie eliminat din 'Mapari salvate' (US-011)."
    )
    assert '"kebab-menu"' not in html, (
        "Clasa 'kebab-menu' trebuie eliminata complet din 'Mapari salvate' (US-011)."
    )


def test_butoane_cu_aria_label(client):
    """Butoanele .act din 'Mapari salvate' au aria-label si iconita Lucide (.act-ic).

    PRD 5.13: aria-label scurt ("Salveaza" / "Sterge") pe butonul .act;
    iconita SVG cu clasa .act-ic (Lucide stroke) prezenta pentru mobil.
    """
    acct = _create_account_user("actiuni_aria@test.com")
    _seed_saved_mapping(acct)
    _login(client, "actiuni_aria@test.com")

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

    act_btns = re.findall(r'<button[^>]+class="act[^"]*"[^>]*>', html)
    assert act_btns, "Trebuie sa existe butoane cu clasa 'act' in 'Mapari salvate'."
    assert any('aria-label' in btn for btn in act_btns), (
        "Cel putin un buton .act trebuie sa aiba atributul aria-label."
    )
    assert 'class="act-ic"' in html, (
        "Iconita Lucide (.act-ic svg) trebuie sa fie prezenta in output (afisata pe mobil)."
    )


def test_dirty_state_data_attr(client):
    """Butonul de salvare are data-dirty-form pentru dirty-state JS."""
    acct = _create_account_user("actiuni_dirty@test.com")
    _seed_saved_mapping(acct)
    _login(client, "actiuni_dirty@test.com")

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

    assert 'data-dirty-form=' in html, (
        "Butonul de salvare trebuie sa aiba atributul data-dirty-form pentru JS dirty-state. "
        "Cand utilizatorul schimba selectul, JS adauga clasa 'dirty' pe buton (fundal --accent)."
    )
