"""Teste US-006 (PRD 3.6): "Formate de coloane salvate" randate ca TABEL.

Doar marcaj de template — POST-urile /formate-coloane/editeaza si /formate-coloane/sterge
raman identice. .tablewrap pentru consistenta cu celelalte tabele.
"""

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("/?tab=mapari")
    m = re.search(r'name="csrf_token"\s+value="([^"]+)"', resp.text) or \
        re.search(r'value="([^"]+)"\s+name="csrf_token"', resp.text)
    assert m
    return m.group(1)


def _seed_format(acct: int, sig: str, mapare: dict, fmt: str | None) -> int:
    from app.db import get_connection
    conn = get_connection()
    try:
        cur = conn.execute(
            "INSERT INTO column_mappings (account_id, signature_coloane, json_mapare, format_data) "
            "VALUES (?, ?, ?, ?)",
            (acct, sig, json.dumps(mapare, ensure_ascii=False), fmt),
        )
        conn.commit()
        return int(cur.lastrowid)
    finally:
        conn.close()


def _slice(text: str, start_marker: str, end_marker: str | None) -> str:
    i = text.index(start_marker)
    j = text.index(end_marker, i) if end_marker else len(text)
    return text[i:j]


@pytest.fixture()
def client(monkeypatch):
    tmp = tempfile.mkdtemp()
    monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "formate_tabel.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_formate_coloane_in_tabel(client):
    """Sectiunea "Formate de coloane salvate" randata ca tabel: nr coloane / mapari / format data / Sterge."""
    acct = _create_account_user("ft@test.com")
    _seed_format(acct, "sig-1", {"Serie sasiu": "vin", "Nr auto": "nr_inmatriculare"}, "DD.MM.YYYY")
    _login(client, "ft@test.com")

    resp = client.get("/?tab=mapari")
    assert resp.status_code == 200
    sec = _slice(resp.text, "Formate de coloane salvate", None)

    assert "tablewrap" in sec, "tabelul Formate trebuie sa foloseasca .tablewrap"
    assert "<table" in sec and "<th" in sec, "Formate trebuie randat ca tabel cu antet"
    # nr coloane + maparile col -> camp
    assert "2" in sec
    assert "Serie sasiu" in sec and "vin" in sec
    # format data editabil prezent
    assert 'name="format_data"' in sec
    assert "DD.MM.YYYY" in sec
    # POST-urile neschimbate
    assert 'hx-post="/formate-coloane/editeaza"' in sec
    assert 'hx-post="/formate-coloane/sterge"' in sec


def test_formate_editare_data_si_stergere_inca_functioneaza(client):
    """POST /formate-coloane/editeaza (schimba format_data) si /sterge neschimbate."""
    acct = _create_account_user("fts@test.com")
    fid = _seed_format(acct, "sig-2", {"Data": "data_prestatie"}, "DD.MM.YYYY")
    _login(client, "fts@test.com")
    csrf = _csrf(client)

    resp = client.post("/formate-coloane/editeaza", data={
        "format_id": str(fid), "format_data": "YYYY-MM-DD", "csrf_token": csrf,
    })
    assert resp.status_code == 200

    from app.db import get_connection
    conn = get_connection()
    try:
        row = conn.execute("SELECT format_data FROM column_mappings WHERE id=?", (fid,)).fetchone()
    finally:
        conn.close()
    assert row["format_data"] == "YYYY-MM-DD"

    resp = client.post("/formate-coloane/sterge", data={"format_id": str(fid), "csrf_token": csrf})
    assert resp.status_code == 200
    conn = get_connection()
    try:
        row = conn.execute("SELECT 1 FROM column_mappings WHERE id=?", (fid,)).fetchone()
    finally:
        conn.close()
    assert row is None
