"""Teste US-003 (PRD 3.4): navigare cu tab-uri (shell dashboard).

TDD: testele se scriu INAINTE de implementare; la inceput pica (RED),
dupa implementare trec (GREEN).

Rute testate:
- GET / -> dashboard cu tab-bar si panou activ randat server-side
- GET /?tab=<name> -> deep-link, panoul corespunzator randat server-side
"""

from __future__ import annotations

import os
import re
import tempfile

import pytest
from starlette.testclient import TestClient


def _create_account_user(email: str = "tabs@test.com", password: str = "parolasecreta10"):
    """Creeaza cont + user. Intoarce (acct_id, user_id)."""
    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 Tabs", active=True)
        user_id = create_user(conn, acct_id, email, password)
        return acct_id, user_id
    finally:
        conn.close()


def _login(client, email: str, password: str) -> None:
    """Face login real prin HTTP si seteaza cookie-ul de sesiune pe client."""
    resp = client.get("/login")
    assert resp.status_code == 200
    m = re.search(r'name="csrf_token"\s+value="([^"]+)"', resp.text)
    if not m:
        m = re.search(r'value="([^"]+)"\s+name="csrf_token"', resp.text)
    assert m, "csrf_token negasit pe /login"
    csrf = m.group(1)

    resp = client.post("/login", data={
        "email": email,
        "parola": password,
        "csrf_token": csrf,
    })
    assert resp.status_code == 303, f"Login esuat: {resp.status_code} {resp.text[:200]}"


@pytest.fixture()
def client(monkeypatch):
    """Client cu BD izolata si autentificare web activata."""
    tmp = tempfile.mkdtemp()
    monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "tabs_test.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()  # izolare: limiterul login e global in-proces
    from app.main import app
    with TestClient(app, follow_redirects=False) as c:
        yield c
    ratelimit._hits.clear()
    get_settings.cache_clear()


# ============================================================
# test_dashboard_are_tabbar
# ============================================================

def test_dashboard_are_tabbar(client):
    """US-009 (5.10): tab-bar-ul eliminat; Mapari mutat in meniul ☰; rutele raman valide."""
    _create_account_user("tabbar@test.com", "parolasecreta10")
    _login(client, "tabbar@test.com", "parolasecreta10")

    resp = client.get("/")
    assert resp.status_code == 200

    html = resp.text
    # US-009: tab-bar-ul (role="tablist") a fost eliminat
    assert 'role="tablist"' not in html, "Tab-bar-ul (role=tablist) trebuie eliminat (US-009)"
    # Cont/Integrare/Nomenclator raman in meniu, nu ca tab-uri
    for label in ("Cont", "Integrare", "Nomenclator", "Import"):
        assert not re.search(rf'role="tab"[^>]*>\s*{label}\s*<', html), \
            f"'{label}' nu ar mai trebui sa fie un tab separat"
    # Mapari e acum in meniu (nu tab), cu link valid
    assert 'href="/?tab=mapari"' in html, "Lipseste link Mapari din meniu"
    # Cont/Nomenclator raman in meniu
    assert 'href="/?tab=cont"' in html and 'href="/?tab=nomenclator"' in html


# ============================================================
# test_tab_implicit_acasa
# ============================================================

def test_tab_implicit_acasa(client):
    """US-009: fara ?tab=, pagina principala randeaza continutul Acasa (upload + sectiuni)."""
    _create_account_user("implicit@test.com", "parolasecreta10")
    _login(client, "implicit@test.com", "parolasecreta10")

    resp = client.get("/")
    assert resp.status_code == 200

    html = resp.text
    # US-009: tab-bar eliminat, deci nu mai exista aria-selected pe tab-uri
    assert 'role="tablist"' not in html, "Tab-bar-ul trebuie eliminat (US-009)"
    # Continutul Acasa (status-bar + tab-panel cu continut Acasa) e randat direct
    assert 'id="status-bar"' in html, "Status-bar-ul trebuie sa fie prezent"
    assert 'id="tab-panel"' in html, "Panoul de continut (tab-panel) trebuie sa fie prezent"


# ============================================================
# test_deeplink_tab_import
# ============================================================

def test_deeplink_tab_import(client):
    """/?tab=import randeaza panoul Import server-side la full load."""
    _create_account_user("deeplink@test.com", "parolasecreta10")
    _login(client, "deeplink@test.com", "parolasecreta10")

    resp = client.get("/?tab=import")
    assert resp.status_code == 200

    html = resp.text
    # Panoul Import trebuie sa contina id="import-section" (din _upload.html)
    assert 'id="import-section"' in html, (
        "Panoul Import nu contine id='import-section' la full load cu ?tab=import"
    )


# ============================================================
# test_tab_activ_randat_server_side
# ============================================================

def test_tab_activ_randat_server_side(client):
    """Panoul activ e in HTML-ul initial, randat server-side (nu doar HTMX dupa load)."""
    _create_account_user("serverside@test.com", "parolasecreta10")
    _login(client, "serverside@test.com", "parolasecreta10")

    # Acasa e randat server-side
    resp = client.get("/")
    assert resp.status_code == 200
    html = resp.text
    # US-009: role="tabpanel" eliminat; continutul e in div#tab-panel fara rol ARIA de tabpanel
    assert 'id="tab-panel"' in html, "Containerul de continut tab-panel trebuie sa existe"
    assert 'role="tabpanel"' not in html, "role=tabpanel trebuie eliminat (US-009)"

    # Import tab server-side: ?tab=import randeaza direct continutul Import
    resp2 = client.get("/?tab=import")
    assert resp2.status_code == 200
    html2 = resp2.text
    assert 'id="import-section"' in html2, "Panoul Import nu e randat server-side la ?tab=import"


# ============================================================
# test_fragmentele_inactive_lazy
# ============================================================

def test_fragmentele_inactive_lazy(client):
    """US-003 (3.6): Trimiterile sunt sectiune pe Acasa, nu un tab separat.

    First-run (zero trimiteri): sectiunea Trimiteri (si poll-ul ei) e suprimata.
    Dupa ce contul are trimiteri, sectiunea apare pe Acasa cu poll-ul ei.
    """
    acct, _ = _create_account_user("lazy@test.com", "parolasecreta10")
    _login(client, "lazy@test.com", "parolasecreta10")

    # First-run: fara trimiteri -> niciun poll de submissions pe Acasa.
    resp = client.get("/")
    assert resp.status_code == 200
    assert "/_fragments/submissions" not in resp.text, (
        "Poll-ul de submissions nu trebuie sa apara cand contul nu are inca trimiteri"
    )

    # Seed o trimitere -> sectiunea Trimiteri apare pe Acasa.
    from app.db import get_connection
    conn = get_connection()
    try:
        conn.execute(
            "INSERT INTO submissions (idempotency_key, account_id, status, payload_json) "
            "VALUES (?, ?, 'sent', '{}')",
            ("k-lazy-1", acct),
        )
        conn.commit()
    finally:
        conn.close()

    resp2 = client.get("/?tab=coada")  # ?tab=coada cade pe Acasa, fara 404
    assert resp2.status_code == 200
    assert "/_fragments/submissions" in resp2.text, (
        "Sectiunea Trimiteri de pe Acasa nu contine referinta la submissions"
    )


# ============================================================
# test_tabbar_aria
# ============================================================

def test_tabbar_aria(client):
    """US-009: schela ARIA orfana (role=tablist/tab/tabpanel/aria-selected) a fost eliminata."""
    _create_account_user("aria@test.com", "parolasecreta10")
    _login(client, "aria@test.com", "parolasecreta10")

    resp = client.get("/")
    assert resp.status_code == 200

    html = resp.text
    # US-009: un role="tablist" cu un singur tab e violare ARIA → eliminat
    assert 'role="tablist"' not in html, "role=tablist trebuie eliminat (US-009)"
    assert 'role="tab"' not in html, "role=tab trebuie eliminat (tab-bar eliminat)"
    assert 'role="tabpanel"' not in html, "role=tabpanel trebuie eliminat (tab-bar eliminat)"
    assert 'aria-selected=' not in html, "aria-selected trebuie eliminat (fara tab-uri)"
    # Meniu cont (role="menu") si item-urile sale (role="menuitem") raman valide
    assert 'role="menu"' in html, "Meniul hamburger (role=menu) trebuie pastrat"
    assert 'role="menuitem"' in html, "Intrarile meniului (role=menuitem) trebuie pastrate"


# ============================================================
# test_fragmentele_mutate_raman_accesibile (US-007)
# ============================================================

def test_fragmentele_mutate_raman_accesibile(client):
    """US-007 (5.5): Cont/Integrare/Nomenclator s-au mutat in meniu, dar rutele de fragment
    si deep-link-ul ?tab= raman valide (zero rute moarte / 404)."""
    _create_account_user("frag@test.com", "parolasecreta10")
    _login(client, "frag@test.com", "parolasecreta10")

    for tab in ("cont", "integrare", "nomenclator"):
        r_frag = client.get(f"/_fragments/{tab}")
        assert r_frag.status_code == 200, f"/_fragments/{tab} a dat {r_frag.status_code}"
        r_deep = client.get(f"/?tab={tab}")
        assert r_deep.status_code == 200, f"/?tab={tab} a dat {r_deep.status_code}"
