"""Teste US-009 (PRD 5.10): Mapari in meniu hamburger + scoatere tab-uri.

TDD: testele se scriu INAINTE de implementare.

Acceptance criteria testate:
- test_meniu_contine_mapari: meniul #cont-menu are o intrare Mapari
  (href=/?tab=mapari); badge vizibil cand exista needs_mapping.
- test_pagina_principala_fara_tabbar_mapari: pagina / nu mai are role="tablist"
  (tab-bar-ul Acasa/Mapari a fost eliminat).
- test_ruta_mapari_randeaza_sectiunea: GET /?tab=mapari → 200, sectiunea mapari
  randata (id="mapari-section"), fara role="tablist" rezidual.
"""

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, 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 Meniu", 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 negasit pe /login"
    resp = client.post("/login", data={"email": email, "parola": password, "csrf_token": m.group(1)})
    assert resp.status_code == 303


def _ins_needs_mapping(acct: int) -> 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 (?, ?, 'needs_mapping', ?)",
            (f"k-us009-{os.urandom(4).hex()}", acct, json.dumps({"prestatii": [{"cod_op_service": "X"}]})),
        )
        conn.commit()
        return int(cur.lastrowid)
    finally:
        conn.close()


@pytest.fixture()
def client(monkeypatch):
    tmp = tempfile.mkdtemp()
    monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "meniu_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()
    from app.main import app
    with TestClient(app, follow_redirects=False) as c:
        yield c
    ratelimit._hits.clear()
    get_settings.cache_clear()


def test_meniu_contine_mapari(client):
    """Meniul hamburger (#cont-menu) contine o intrare cu href=/?tab=mapari."""
    _create_account_user("menu1@test.com")
    _login(client, "menu1@test.com")

    html = client.get("/").text

    # Intrarea Mapari trebuie sa existe in meniu
    assert 'href="/?tab=mapari"' in html, (
        "Meniul hamburger trebuie sa contina o intrare cu href='/?tab=mapari'"
    )
    # Textul "Mapari" trebuie sa apara in meniu (in apropierea link-ului)
    idx = html.find('href="/?tab=mapari"')
    assert idx != -1
    # Cauta "Mapari" in fereastra contextului link-ului
    window = html[max(0, idx - 50):idx + 100]
    assert "Mapari" in window, (
        f"Textul 'Mapari' trebuie sa apara langa href=/?tab=mapari: ...{window}..."
    )


def test_meniu_badge_needs_mapping(client):
    """Badge vizibil in meniu cand exista submissions needs_mapping."""
    acct = _create_account_user("menu2@test.com")
    _ins_needs_mapping(acct)
    _login(client, "menu2@test.com")

    html = client.get("/").text

    # Badgeul trebuie sa apara in apropierea intrarii Mapari
    idx = html.find('href="/?tab=mapari"')
    assert idx != -1, "Intrarea Mapari lipseste din meniu"
    # Cauta tab-badge in contextul intrarii Mapari (in tag-ul/blocul imediat urmator)
    window = html[idx:idx + 300]
    assert "tab-badge" in window, (
        "Badgeul (tab-badge) trebuie sa apara in intrarea Mapari cand exista needs_mapping"
    )


def test_pagina_principala_fara_tabbar_mapari(client):
    """Pagina principala / nu mai are role=tablist (tab-bar-ul eliminat in US-009)."""
    _create_account_user("menu3@test.com")
    _login(client, "menu3@test.com")

    html = client.get("/").text

    assert 'role="tablist"' not in html, (
        "Tab-bar-ul (role=tablist) trebuie eliminat din pagina principala (US-009)"
    )
    # Nici rolul de tab individual nu trebuie sa existe in tab-bar
    # (role=tab poate exista in alte contexte, dar tab-bar-ul tablist+tab nu)
    assert 'class="tab-bar"' not in html, (
        "Clasa CSS tab-bar trebuie eliminata din pagina principala (US-009)"
    )


def test_ruta_mapari_randeaza_sectiunea(client):
    """GET /?tab=mapari → 200, sectiunea mapari randata, fara tablist rezidual."""
    _create_account_user("menu4@test.com")
    _login(client, "menu4@test.com")

    resp = client.get("/?tab=mapari")

    assert resp.status_code == 200, (
        f"/?tab=mapari trebuie sa returneze 200, nu {resp.status_code}"
    )
    html = resp.text
    assert 'id="mapari-section"' in html, (
        "Sectiunea mapari (id='mapari-section') trebuie randata la /?tab=mapari"
    )
    assert 'role="tablist"' not in html, (
        "Tab-bar-ul (role=tablist) nu trebuie sa apara nici la /?tab=mapari"
    )
