"""Teste US-001 (PRD 5.10): fix filtrare pe interval de data in fragment_submissions.

Cazuri:
- timestamp-uri cu ora (ex. "2026-06-20 14:35:07") trebuie incluse la filtrare pe ziua respectiva
- interval inclusiv la ambele capete
- valori ne-ISO raman excluse
"""

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, 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) or \
        re.search(r'value="([^"]+)"\s+name="csrf_token"', resp.text)
    assert m
    resp = client.post(
        "/login",
        data={"email": email, "parola": password, "csrf_token": m.group(1)},
    )
    assert resp.status_code == 303


def _ins(acct: int, *, status: str = "queued", vin: str, nr: str, data: str) -> 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(5).hex()}", acct, status,
                json.dumps({
                    "vin": vin,
                    "nr_inmatriculare": nr,
                    "data_prestatie": data,
                    "odometru_final": "100",
                    "prestatii": [{"cod_prestatie": "R-X"}],
                }),
            ),
        )
        conn.commit()
        return cur.lastrowid  # type: ignore[return-value]
    finally:
        conn.close()


def _row(sid: int) -> str:
    """Selector HTML pentru randul cu ID-ul dat."""
    return f'id="trimitere-row-{sid}"'


@pytest.fixture()
def client(monkeypatch):
    tmp = tempfile.mkdtemp()
    monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "filtre_data.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_filtru_data_include_timestamp_cu_ora(client):
    """Un rand cu data_prestatie = '2026-06-20 14:35:07' trebuie sa apara
    cand filtrul e data_de=2026-06-20 si data_pana=2026-06-20.
    Bug actual: _is_iso_date verifica len==10 → exclude timestamp → randul dispare."""
    acct = _create_account_user("ts_ora@test.com")
    # timestamp cu ora — asta e cauza bug-ului
    sid_ora = _ins(acct, vin="WVIN001TS001ORA0001", nr="B01TS", data="2026-06-20 14:35:07")
    # rand fara ora, in afara intervalului (nu trebuie sa apara)
    sid_alt = _ins(acct, vin="WVIN001TS001ALT0002", nr="B02TS", data="2026-06-21")
    _login(client, "ts_ora@test.com")

    resp = client.get("/_fragments/submissions?data_de=2026-06-20&data_pana=2026-06-20")
    assert resp.status_code == 200
    assert _row(sid_ora) in resp.text, (
        "Timestamp-ul cu ora trebuie inclus la filtrare pe ziua respectiva"
    )
    assert _row(sid_alt) not in resp.text, (
        "Randul din 2026-06-21 nu trebuie sa apara in intervalul 2026-06-20 to 2026-06-20"
    )


def test_filtru_data_interval_inclusiv_capete(client):
    """Intervalul data_de..data_pana este inclusiv la ambele capete.
    data_de=2026-06-10, data_pana=2026-06-12 → randurile din 10, 11, 12 apar;
    cel din 09 si cel din 13 nu apar.
    Testat si cu timestamp-uri (ISO cu ora) pentru a combina ambele cerinte."""
    acct = _create_account_user("interval@test.com")
    sid_09 = _ins(acct, vin="WVIN_INTERVAL_09000", nr="B09", data="2026-06-09")
    sid_10 = _ins(acct, vin="WVIN_INTERVAL_10000", nr="B10", data="2026-06-10")               # capat stang inclusiv
    sid_11 = _ins(acct, vin="WVIN_INTERVAL_11000", nr="B11", data="2026-06-11 08:00:00")       # mijloc cu ora
    sid_12 = _ins(acct, vin="WVIN_INTERVAL_12000", nr="B12", data="2026-06-12T23:59:59")       # capat drept cu T
    sid_13 = _ins(acct, vin="WVIN_INTERVAL_13000", nr="B13", data="2026-06-13")
    _login(client, "interval@test.com")

    resp = client.get("/_fragments/submissions?data_de=2026-06-10&data_pana=2026-06-12")
    assert resp.status_code == 200
    body = resp.text
    assert _row(sid_09) not in body, "2026-06-09 e inainte de data_de → nu trebuie sa apara"
    assert _row(sid_10) in body, "2026-06-10 = data_de → capatul stang inclusiv"
    assert _row(sid_11) in body, "2026-06-11 cu ora trebuie inclus"
    assert _row(sid_12) in body, "2026-06-12 cu T trebuie inclus (capatul drept inclusiv)"
    assert _row(sid_13) not in body, "2026-06-13 e dupa data_pana → nu trebuie sa apara"


def test_filtru_data_ignora_valori_ne_data(client):
    """Valorile care nu incep cu o data ISO valida sunt excluse din rezultate
    cand filtrul de data e activ — comportamentul actual pastrat."""
    acct = _create_account_user("nedata@test.com")
    sid_dd  = _ins(acct, vin="WVIN_NEDATA_DD000001", nr="BND1", data="20.06.2026")   # format DD.MM.YYYY — ne-ISO
    sid_en  = _ins(acct, vin="WVIN_NEDATA_EN000002", nr="BND2", data="Jun 20 2026")  # format englezesc — ne-ISO
    sid_bun = _ins(acct, vin="WVIN_NEDATA_BUNA0003", nr="BGD",  data="2026-06-20")   # format corect ISO
    _login(client, "nedata@test.com")

    resp = client.get("/_fragments/submissions?data_de=2026-06-20&data_pana=2026-06-20")
    assert resp.status_code == 200
    body = resp.text
    assert _row(sid_dd) not in body, "Format DD.MM.YYYY trebuie exclus (ne-ISO)"
    assert _row(sid_en) not in body, "Format englezesc trebuie exclus (ne-ISO)"
    assert _row(sid_bun) in body, "Format ISO corect trebuie inclus"
