"""Teste US-003 (PRD 3.6): Acasa unificata — Trimiteri ca sectiune permanenta.

Tab-ul "Trimiteri" (coada) eliminat din tab-bar; Trimiterile devin o sectiune sub
upload pe Acasa, cu heading "Trimiterile tale". ?tab=coada si /_fragments/coada
servesc continutul Acasa (nu 404, nu fragment orfan). Poll aliniat la 15s (M5).
"""

from __future__ import annotations

import json
import os
import tempfile

import pytest
from fastapi.testclient import TestClient


@pytest.fixture()
def client(monkeypatch):
    tmp = tempfile.mkdtemp()
    monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "acasa.db"))
    monkeypatch.setenv("AUTOPASS_WEB_AUTH_REQUIRED", "false")
    from app.config import get_settings
    get_settings.cache_clear()
    from app.crypto import reset_cache
    reset_cache()
    from app.main import app
    with TestClient(app) as c:
        yield c
    get_settings.cache_clear()
    reset_cache()


def _seed_submission(status: str = "sent", n: int = 1) -> None:
    from app.db import get_connection
    conn = get_connection()
    try:
        for i in range(n):
            conn.execute(
                "INSERT INTO submissions (idempotency_key, account_id, status, payload_json) "
                "VALUES (?, 1, ?, ?)",
                (f"k-{status}-{os.urandom(5).hex()}", status,
                 json.dumps({"vin": "WVWZZZ1KZAW000123", "nr_inmatriculare": "B001TST",
                             "data_prestatie": "2026-06-10", "odometru_final": "123456",
                             "prestatii": [{"cod_prestatie": "R-FRANE"}]})),
            )
        conn.commit()
    finally:
        conn.close()


def test_tab_bar_fara_trimiteri(client):
    """US-009: tab-bar eliminat; 'Coada' nu exista; Mapari/Cont/Nomenclator raman in meniu."""
    r = client.get("/")
    assert r.status_code == 200
    html = r.text
    # "Coada" nu trebuie sa existe nici ca tab, nici ca link in meniu
    assert 'id="tab-coada"' not in html
    assert 'href="/?tab=coada"' not in html
    # US-009: tab-bar eliminat; Mapari/Cont/Nomenclator sunt in meniul hamburger
    for label in ("Mapari", "Cont", "Nomenclator"):
        assert f">{label}" in html or f"{label}<" in html, f"lipseste intrarea {label} in meniu"


def test_acasa_contine_sectiunea_trimiteri(client):
    """Acasa randeaza sectiunea Trimiteri (filtre + tabel) cand contul are trimiteri."""
    _seed_submission("sent")
    r = client.get("/?tab=acasa")
    assert r.status_code == 200
    html = r.text
    assert 'id="filtre-trimiteri"' in html
    assert "/_fragments/submissions" in html
    # PRD 5.9 US-003: detaliul s-a mutat in modalul global (#modal-detaliu); vechiul
    # panou inert #trimitere-detaliu a fost eliminat.
    assert 'id="modal-detaliu"' in html
    assert 'id="trimitere-detaliu"' not in html


def test_sectiune_trimiteri_are_heading(client):
    """Sectiunea Trimiteri are heading 'Trimiterile tale'."""
    _seed_submission("sent")
    r = client.get("/?tab=acasa")
    assert "Trimiterile tale" in r.text


def test_tab_coada_redirect_la_acasa(client):
    """?tab=coada nu da 404 si serveste continutul Acasa (upload-ul de import)."""
    r = client.get("/?tab=coada")
    assert r.status_code == 200
    assert 'id="import-section"' in r.text or 'id="acasa-section"' in r.text


def test_fragment_coada_serveste_acasa(client):
    """/_fragments/coada serveste continutul Acasa (fara fragment _coada orfan)."""
    _seed_submission("sent")
    r = client.get("/_fragments/coada")
    assert r.status_code == 200
    html = r.text
    assert 'id="acasa-section"' in html
    assert "Trimiterile tale" in html


def test_acasa_fara_linkuri_ajutor(client):
    """Linkul redundant 'Trimiteri' din randul de ajutor a fost eliminat."""
    _seed_submission("sent")
    r = client.get("/?tab=acasa")
    assert 'href="/?tab=coada"' not in r.text


def test_acasa_fara_wayfinding_ajutor(client):
    """US-001 (5.5): randul 'Ajutor' (wayfinding Mapari/Coduri RAR) eliminat din Acasa —
    navigarea traieste in tab-bar si in meniul de cont."""
    r = client.get("/?tab=acasa")
    html = r.text
    assert "Ajutor:" not in html
    assert "Coduri RAR" not in html


def test_badge_trimiteri_scoped_pe_acasa(client):
    """Contorul de atentie (blocate) se reflecta in heading-ul sectiunii Trimiteri."""
    _seed_submission("needs_data", n=2)
    r = client.get("/?tab=acasa")
    html = r.text
    assert "Trimiterile tale" in html
    # Badge cu numarul de blocate (2) langa heading.
    idx = html.find("Trimiterile tale")
    assert idx != -1
    assert "2" in html[idx:idx + 400]


def test_trimiteri_fara_poll_periodic_pe_tabel(client):
    """Tabelul de trimiteri NU se reimprospateaza periodic: #submissions-wrap se
    incarca la load / actiunile utilizatorului (trimiteriChanged) / reincarcaTrimiteri.
    Reimprospatarea automata la date noi externe se face prin pollerul de versiune
    care cheama reincarcaTrimiteri() — fara nudge manual (US-008)."""
    _seed_submission("sent")
    r = client.get("/?tab=acasa")
    html = r.text
    # Trigger-ul tabelului nu contine poll periodic.
    wrap = html[html.find('id="submissions-wrap"'):]
    wrap = wrap[:wrap.find(">") + 1]
    assert "every" not in wrap, f"tabelul nu trebuie sa aiba poll periodic: {wrap}"
    assert "reincarcaTrimiteri" in wrap
    assert "trimiteriChanged" in wrap
    # Pollerul de versiune exista (auto-refresh la date noi externe). Nudge eliminat (US-008).
    assert "/_fragments/trimiteri-versiune" in html
    assert 'id="nudge-trimiteri"' not in html
