"""Teste US-007 (PRD 3.5): pagina "Mapari" cu 3 sectiuni; "Cont" fara mapari."""

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 _seed(acct: int) -> None:
    from app.db import get_connection
    conn = get_connection()
    try:
        conn.execute("INSERT OR REPLACE INTO nomenclator_rar (cod_prestatie, nume_prestatie) VALUES ('R-FRANE','Reparatie frane')")
        conn.execute(
            "INSERT INTO operations_mapping (account_id, cod_op_service, cod_prestatie, auto_send) VALUES (?, 'OP-1', 'R-FRANE', 1)",
            (acct,),
        )
        conn.execute(
            "INSERT INTO column_mappings (account_id, signature_coloane, json_mapare, format_data) VALUES (?, 'sig-x', ?, 'DD.MM.YYYY')",
            (acct, json.dumps({"Serie sasiu": "vin"})),
        )
        conn.commit()
    finally:
        conn.close()


@pytest.fixture()
def client(monkeypatch):
    tmp = tempfile.mkdtemp()
    monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "mapari_ui.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_mapari_trei_sectiuni(client):
    """Fragmentul /_fragments/mapari contine cele 3 sectiuni."""
    acct = _create_account_user("m3@test.com")
    _seed(acct)
    _login(client, "m3@test.com")

    resp = client.get("/_fragments/mapari")
    assert resp.status_code == 200
    html = resp.text
    assert "De rezolvat" in html
    assert "Mapari operatii salvate" in html
    assert "Formate de coloane salvate" in html
    # Maparea salvata si formatul apar
    assert "OP-1" in html
    assert "Serie sasiu" in html


def test_mapari_sectiuni_goale_au_mesaj(client):
    """Sectiunile goale au mesaj prietenos, nu lipsesc tacit."""
    _create_account_user("mgol@test.com")
    _login(client, "mgol@test.com")

    resp = client.get("/_fragments/mapari")
    assert resp.status_code == 200
    html = resp.text
    # Toate cele 3 titluri prezente chiar si cand sunt goale
    assert "De rezolvat" in html
    assert "Mapari operatii salvate" in html
    assert "Formate de coloane salvate" in html
    assert "Nicio mapare salvata" in html
    assert "Niciun format de coloane salvat" in html


def test_cont_fara_mapari(client):
    """/_fragments/cont nu mai contine sectiuni de mapari."""
    _create_account_user("cfm@test.com")
    _login(client, "cfm@test.com")

    resp = client.get("/_fragments/cont")
    assert resp.status_code == 200
    html = resp.text
    assert "Mapari operatii salvate" not in html
    assert "Formate de coloane salvate" not in html
    # Cont contine doar cheie API + creds RAR
    assert "Cheia mea API" in html
    assert "Credentiale RAR" in html
