"""Teste TDD US-009 (PRD 5.15): salvare mapare din chip + cleanup (B) select redundant.

RED -> implementare -> GREEN.

AC-uri verificate:
  - Endpoint /trimitere/{id}/salveaza-regula-chip salveaza regula via save_mapping+reresolve_account.
  - Re-rezolvarea deblocheaza si submission-uri frate cu aceeasi operatie (batch_id IS NULL).
  - Editarea one-off prin /corecteaza nu forteaza salvarea regulii in operations_mapping.
  - Cleanup (B): detaliu needs_data NU mai contine <select name="cod_prestatie"> simultan cu chips.
"""

from __future__ import annotations

import json
import os
import re
import tempfile

import pytest
from starlette.testclient import TestClient


# --------------------------------------------------------------------------- #
# Fixtures                                                                     #
# --------------------------------------------------------------------------- #

@pytest.fixture()
def client(monkeypatch):
    tmp = tempfile.mkdtemp()
    monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "chip_mapare.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()


# --------------------------------------------------------------------------- #
# Helpere                                                                      #
# --------------------------------------------------------------------------- #

def _create_account_user(email: str, 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, "Service Test US009", 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, "csrf_token nu gasit in login"
    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=coada")
    m = re.search(r'name="csrf_token"\s+value="([^"]+)"', resp.text)
    assert m, "csrf_token nu gasit in dashboard"
    return m.group(1)


def _insert(acct: int, *, status: str, payload: dict) -> int:
    from app.db import get_connection
    conn = get_connection()
    try:
        cur = conn.execute(
            "INSERT INTO submissions (idempotency_key, account_id, status, payload_json) "
            "VALUES (?, ?, ?, ?)",
            (f"k-{os.urandom(6).hex()}", acct, status, json.dumps(payload)),
        )
        conn.commit()
        return int(cur.lastrowid)
    finally:
        conn.close()


def _row(sid: int):
    from app.db import get_connection
    conn = get_connection()
    try:
        return conn.execute("SELECT * FROM submissions WHERE id=?", (sid,)).fetchone()
    finally:
        conn.close()


def _seed_cod(cod: str, denumire: str = "Prestatie test") -> 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, denumire),
        )
        conn.commit()
    finally:
        conn.close()


def _get_rule(acct: int, op: str):
    """Cauta regula op->cod in operations_mapping pentru cont + operatie."""
    from app.db import get_connection
    conn = get_connection()
    try:
        return conn.execute(
            "SELECT cod_prestatie FROM operations_mapping WHERE account_id=? AND cod_op_service=?",
            (acct, op),
        ).fetchone()
    finally:
        conn.close()


# --------------------------------------------------------------------------- #
# Test 1: Salvare regula din chip (US-009 AC1)                                #
# --------------------------------------------------------------------------- #

def test_salveaza_regula_din_chip(client):
    """US-009 AC1: POST /trimitere/{id}/salveaza-regula-chip -> save_mapping + reresolve.

    RED: endpoint-ul nu exista inca; trebuie creat cu reuse EXACT save_mapping+reresolve_account.
    """
    acct = _create_account_user("save.chip@test.com")
    _login(client, "save.chip@test.com")
    _seed_cod("OE-1", "Schimb ulei motor")

    op = "Schimb ulei motor"
    sid = _insert(acct, status="needs_mapping", payload={
        "vin": "WVWZZZ1JZXW0SC001",
        "nr_inmatriculare": "B100AAA",
        "data_prestatie": "2026-06-10",
        "odometru_final": "50000",
        "prestatii": [{"cod_op_service": op, "denumire": "Schimb ulei 5W30"}],
    })
    csrf = _csrf(client)

    # Salveaza regula din chip (endpoint nou US-009)
    resp = client.post(
        f"/trimitere/{sid}/salveaza-regula-chip",
        data={
            "csrf_token": csrf,
            "salveaza_op": op,
            "salveaza_cod": "OE-1",
        },
    )
    assert resp.status_code == 200, (
        f"Endpoint-ul salveaza-regula-chip a returnat {resp.status_code}: {resp.text[:500]}"
    )

    # Regula trebuie salvata in operations_mapping
    rule = _get_rule(acct, op)
    assert rule is not None, (
        f"Regula nu a fost salvata in operations_mapping: op={op!r}"
    )
    assert rule["cod_prestatie"] == "OE-1", (
        f"Codul salvat e gresit: {rule['cod_prestatie']!r} (asteptat OE-1)"
    )

    # Submission-ul propriu trebuie re-rezolvat (reresolve_account e apelat)
    r = _row(sid)
    assert r["status"] == "queued", (
        f"Dupa salvarea regulii, submission-ul trebuia sa fie queued, got {r['status']!r}"
    )
    # Nota: mesajul de confirmare ("Regula salvata...") e in context dar flash-ul
    # e randat in sectiunea editabila; dupa re-rezolvare la queued, detaliu e read-only.
    # Verificarile esentiale (rule in DB + status queued) sunt de ajuns pentru US-009 AC1.


# --------------------------------------------------------------------------- #
# Test 2: Re-rezolvare deblocheaza submission frate (US-009 AC2)              #
# --------------------------------------------------------------------------- #

def test_reresolve_deblocheaza_frate(client):
    """US-009 AC2: salvarea regulii din chip deblocheaza si alt submission needs_mapping
    cu aceeasi operatie (canal API — batch_id IS NULL → reresolve_account scoped null).

    RED: endpoint-ul nu exista; dupa implementare, reresolve_account re-rezolva ambele.
    """
    acct = _create_account_user("frate.deblocat@test.com")
    _login(client, "frate.deblocat@test.com")
    _seed_cod("OE-1", "Schimb ulei motor")

    op = "Schimb ulei motor"

    # Doua submission-uri cu aceeasi operatie, ambele needs_mapping, batch_id=NULL (API)
    sid1 = _insert(acct, status="needs_mapping", payload={
        "vin": "WVWZZZ1JZXW0RD001",
        "nr_inmatriculare": "B100AAA",
        "data_prestatie": "2026-06-10",
        "odometru_final": "50000",
        "prestatii": [{"cod_op_service": op, "denumire": "Schimb ulei 5W30"}],
    })
    sid2 = _insert(acct, status="needs_mapping", payload={
        "vin": "WVWZZZ1JZXW0RD002",
        "nr_inmatriculare": "B200BBB",
        "data_prestatie": "2026-06-11",
        "odometru_final": "60000",
        "prestatii": [{"cod_op_service": op, "denumire": "Schimb ulei 5W30"}],
    })
    csrf = _csrf(client)

    # Salveaza regula din chip pentru sid1 -> reresolve_account deblocheaza si sid2
    resp = client.post(
        f"/trimitere/{sid1}/salveaza-regula-chip",
        data={
            "csrf_token": csrf,
            "salveaza_op": op,
            "salveaza_cod": "OE-1",
        },
    )
    assert resp.status_code == 200, resp.text[:500]

    # sid1 trebuie sa fie re-rezolvat
    r1 = _row(sid1)
    assert r1["status"] == "queued", (
        f"sid1 trebuia sa fie queued dupa salvarea regulii, got {r1['status']!r}"
    )

    # sid2 (fratele) trebuie sa fie de asemenea re-rezolvat de reresolve_account
    r2 = _row(sid2)
    assert r2["status"] == "queued", (
        f"sid2 (fratele) trebuia sa fie deblocat (queued) de reresolve_account, "
        f"got {r2['status']!r}. reresolve_account trebuie sa re-rezolve TOATE "
        f"submission-urile cu aceeasi operatie pe canalul API (batch_id IS NULL)."
    )


# --------------------------------------------------------------------------- #
# Test 3: Editare one-off nu forteaza salvarea regulii (US-009 AC3)           #
# --------------------------------------------------------------------------- #

def test_optional_nu_forteaza(client):
    """US-009 AC3: editarea ramane one-off daca userul nu apeleaza salveaza-regula-chip.

    POST-ul la /corecteaza (fara /salveaza-regula-chip) trebuie sa functioneze normal;
    nicio regula nu se salveaza automat in operations_mapping.

    RED: daca /corecteaza ar salva automat regula (nedorit), testul pica.
    """
    acct = _create_account_user("optional.oneoff@test.com")
    _login(client, "optional.oneoff@test.com")
    _seed_cod("OE-1", "Schimb ulei")

    op = "Schimb ulei special 0W20"
    sid = _insert(acct, status="needs_mapping", payload={
        "vin": "WVWZZZ1JZXW0AP009",
        "nr_inmatriculare": "B100AAA",
        "data_prestatie": "2026-06-10",
        "odometru_final": "50000",
        "prestatii": [{"cod_op_service": op, "denumire": "Ulei sintetic 0W20"}],
    })
    csrf = _csrf(client)

    # Corecteaza one-off (direct la /corecteaza, fara /salveaza-regula-chip)
    resp = client.post(
        f"/trimitere/{sid}/corecteaza",
        data={"csrf_token": csrf, "cod_prestatie": "OE-1"},
    )
    assert resp.status_code == 200
    r = _row(sid)
    assert r["status"] == "queued", (
        f"Status trebuia sa fie queued dupa corectie one-off, got {r['status']!r}"
    )

    # Regula NU trebuie salvata automat in operations_mapping
    rule = _get_rule(acct, op)
    assert rule is None, (
        f"Regula a fost salvata AUTOMAT in operations_mapping (nu ar trebui!): "
        f"op={op!r}, rule={dict(rule) if rule else None}. "
        "Salvarea regulii trebuie sa fie OPTIONALA (US-009 AC3)."
    )


# --------------------------------------------------------------------------- #
# Test 4: Cleanup (B) — <select name="cod_prestatie"> redundant eliminat      #
# --------------------------------------------------------------------------- #

def test_fara_select_vechi_redundant(client):
    """Cleanup (B): detaliu needs_data NU mai contine <select name='cod_prestatie'>.

    Dupa cleanup, formularul editabil foloseste NUMAI chips (hidden inputs cod_prestatie),
    fara vechiul select dublu. Chips functioneaza ca singura sursa de cod_prestatie.

    Nota: <select name="cod_prestatie"> RAMANE in formularul /repune pentru starea error
    (neschimbat — nu e subiectul cleanup-ului B).

    RED: inainte de cleanup, atat selectul cat si chips emit cod_prestatie → dublu.
    """
    acct = _create_account_user("no.select.vechi@test.com")
    _login(client, "no.select.vechi@test.com")
    _seed_cod("OE-1", "Schimb ulei")

    # needs_data: starea editabila (editabil=True); chip cu cod setat
    sid = _insert(acct, status="needs_data", payload={
        "vin": "WVWZZZ1JZXW0NS001",
        "nr_inmatriculare": "B200AA",
        "data_prestatie": "2026-06-20",
        "odometru_final": "",  # gol -> needs_data
        "prestatii": [{"cod_prestatie": "OE-1", "cod_op_service": "Op-A", "denumire": "Schimb ulei"}],
    })

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

    # Chipurile trebuie sa fie prezente (hidden input cu name="cod_prestatie")
    has_chip_hidden = (
        re.search(r'<input[^>]+type=["\']hidden["\'][^>]+name=["\']cod_prestatie["\']', html) or
        re.search(r'<input[^>]+name=["\']cod_prestatie["\'][^>]+type=["\']hidden["\']', html)
    )
    assert has_chip_hidden, (
        "Chips: trebuie sa existe input hidden cu name='cod_prestatie' (din _chips_prestatii.html). "
        f"html[:600]={html[:600]}"
    )

    # Vechiul <select name="cod_prestatie"> NU trebuie sa existe in sectiunea editabila.
    # (needs_data nu are formular /repune, deci niciun select cu name="cod_prestatie" legal)
    select_cod_prestatie = (
        re.search(r'<select[^>]+name=["\']cod_prestatie["\']', html) or
        re.search(r'<select[^>]*name="cod_prestatie"', html)
    )
    assert not select_cod_prestatie, (
        "Sectiunea editabila needs_data NU trebuie sa mai contina "
        "<select name='cod_prestatie'>. "
        "Chips-urile (hidden inputs) il inlocuiesc (cleanup B, US-009). "
        f"Gasit: {select_cod_prestatie.group(0) if select_cod_prestatie else 'N/A'}. "
        f"html[:800]={html[:800]}"
    )
