"""Teste US-007 (PRD 3.6) actualizate dupa US-002 (PRD 5.11).

US-002: macro autosend_toggle neutralizat (intoarce string gol).
Checkbox-ul name=auto_send a fost scos din UI. Coloanele DB raman.
Testele de UI verifica ABSENTA toggle-ului; testele de backend (stocare DB) raman.
"""

from __future__ import annotations

import csv
import io
import os
import re
import tempfile

import pytest
from starlette.testclient import TestClient


# --- helpers comune (mirror test_mapari_tabel.py) ---

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)
    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)
    assert m, "csrf_token negasit"
    return m.group(1)


def _seed_nomenclator(cod: str, nume: str = "Test prestatie") -> None:
    from app.db import get_connection
    conn = get_connection()
    try:
        conn.execute(
            "INSERT OR REPLACE INTO nomenclator_rar (cod_prestatie, nume_prestatie) VALUES (?, ?)",
            (cod, nume),
        )
        conn.commit()
    finally:
        conn.close()


def _auto_send_of(acct: int, op: str) -> int | None:
    from app.db import get_connection
    conn = get_connection()
    try:
        r = conn.execute(
            "SELECT auto_send FROM operations_mapping WHERE account_id=? AND cod_op_service=?",
            (acct, op),
        ).fetchone()
        return None if r is None else int(r["auto_send"])
    finally:
        conn.close()


@pytest.fixture()
def client(monkeypatch):
    tmp = tempfile.mkdtemp()
    monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "autosend_toggle.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 _macro_html(checked: bool = True, form_id: str = "") -> str:
    """Randeaza direct macro-ul, izolat de restul paginii."""
    from app.web.routes import templates
    mod = templates.env.get_template("_macros.html").make_module({})
    return str(mod.autosend_toggle(form_id=form_id, checked=checked))


# --- markup: macro neutralizat dupa US-002 ---

def test_comutator_coada_prezent():
    """US-002: macro autosend_toggle neutralizat -> output gol (fara checkbox)."""
    html = _macro_html()
    assert 'name="auto_send"' not in html, "US-002: checkbox auto_send scos din UI"
    assert html.strip() == "", f"macro neutralizat trebuie sa intoarca string gol, got: {html!r}"


def test_eticheta_scoped_pe_operatie():
    """US-002: macro neutralizat -> nicio eticheta scoped."""
    html = _macro_html()
    assert "aceasta operatie" not in html
    assert html.strip() == ""


def test_default_pune_automat():
    """US-002: macro neutralizat intoarce gol indiferent de parametrul checked."""
    html_default = _macro_html(checked=True)
    assert html_default.strip() == ""
    html_off = _macro_html(checked=False)
    assert html_off.strip() == ""


# --- comportament (zero atingere backend) ---

def test_pune_automat_mapeaza_auto_send_true(client):
    """Bifat -> auto_send=true trimis -> stocat True (identic cu azi)."""
    acct = _create_account_user("pa@test.com")
    _seed_nomenclator("R-FRANE")
    _login(client, "pa@test.com")
    csrf = _csrf(client)
    resp = client.post("/mapari", data={
        "cod_op_service": "OP-A", "cod_prestatie": "R-FRANE",
        "auto_send": "true", "csrf_token": csrf,
    })
    assert resp.status_code == 200
    assert _auto_send_of(acct, "OP-A") == 1


def test_tine_pentru_verificare_mapeaza_auto_send_false(client):
    """Nebifat -> camp absent -> stocat False (semantica de prezenta a checkbox-ului)."""
    acct = _create_account_user("tv@test.com")
    _seed_nomenclator("R-FRANE")
    _login(client, "tv@test.com")
    csrf = _csrf(client)
    # "Tine pentru verificare" = comutatorul nebifat -> name=auto_send NU se trimite
    resp = client.post("/mapari", data={
        "cod_op_service": "OP-B", "cod_prestatie": "R-FRANE", "csrf_token": csrf,
    })
    assert resp.status_code == 200
    assert _auto_send_of(acct, "OP-B") == 0


# --- prezent in AMBELE locuri (mapari tab + panou preview) ---

def test_comutator_in_tab_mapari(client):
    """US-002: tabul Mapari nu mai contine checkbox auto_send (macro neutralizat)."""
    from app.db import get_connection
    import json
    acct = _create_account_user("tm@test.com")
    _seed_nomenclator("R-FRANE")
    conn = get_connection()
    try:
        conn.execute(
            "INSERT INTO submissions (idempotency_key, account_id, status, payload_json) "
            "VALUES (?, ?, 'needs_mapping', ?)",
            ("k-tm", acct, json.dumps({"prestatii": [{"cod_op_service": "OP-NM", "denumire": "x"}]})),
        )
        conn.commit()
    finally:
        conn.close()
    _login(client, "tm@test.com")
    resp = client.get("/?tab=mapari")
    assert resp.status_code == 200
    assert 'name="auto_send"' not in resp.text, "US-002: checkbox auto_send scos din UI"
    assert "In coada" not in resp.text, "US-002: coloana 'In coada' scoasa"


def test_comutator_in_panou_preview(client):
    """US-002: panoul de mapare din preview nu mai contine checkbox auto_send."""
    _create_account_user("pp@test.com")
    _seed_nomenclator("R-FRANE")
    _login(client, "pp@test.com")
    csrf = _csrf(client)

    buf = io.StringIO()
    w = csv.DictWriter(buf, fieldnames=["VIN", "Nr", "Data", "Odo", "Operatie"], delimiter=";")
    w.writeheader()
    w.writerow({"VIN": "WVWZZZ1KZAW000123", "Nr": "B001TST",
                "Data": "15.06.2026", "Odo": "123456", "Operatie": "OP-NEMAPAT"})
    data = buf.getvalue().encode("utf-8")

    r = client.post("/_import/upload", files={"file": ("t.csv", data, "text/csv")},
                    data={"csrf_token": csrf})
    assert r.status_code == 200
    m = re.search(r"/_import/(\d+)/mapare-coloane", r.text)
    assert m
    import_id = int(m.group(1))
    r = client.post(f"/_import/{import_id}/mapare-coloane", data={
        "colname": ["VIN", "Nr", "Data", "Odo", "Operatie"],
        "canon": ["vin", "nr_inmatriculare", "data_prestatie", "odometru_final", "operatie"],
        "format_data": "DD.MM.YYYY", "csrf_token": csrf,
    })
    assert r.status_code == 200
    assert "OP-NEMAPAT" in r.text, "operatia nemapata trebuie sa apara in panoul de mapare"
    assert 'name="auto_send"' not in r.text, "US-002: checkbox auto_send scos din preview"
    assert "In coada automat" not in r.text, "US-002: eticheta 'In coada automat' scoasa"
