"""Teste US-004 (PRD 3.6): zona de upload comprimata la o bara slim.

Cand contul are deja trimiteri, upload-ul devine o bara pe un rand (eticheta + buton
+ zona de trage). First-run pastreaza hero-ul "Primul fisier?". Drag-drop + input file
+ select-foaie (multi-sheet) raman functionale.
"""

from __future__ import annotations

import io
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, "slim.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() -> None:
    from app.db import get_connection
    conn = get_connection()
    try:
        conn.execute(
            "INSERT INTO submissions (idempotency_key, account_id, status, payload_json) "
            "VALUES (?, 1, 'sent', ?)",
            (f"k-{os.urandom(5).hex()}",
             json.dumps({"vin": "WVWZZZ1KZAW000123", "prestatii": [{"cod_prestatie": "R-FRANE"}]})),
        )
        conn.commit()
    finally:
        conn.close()


def _multi_sheet_xlsx() -> bytes:
    openpyxl = pytest.importorskip("openpyxl")
    wb = openpyxl.Workbook()
    ws1 = wb.active
    ws1.title = "Iunie"
    ws1.append(["VIN", "Nr inmatriculare", "Data prestatie", "Odometru final", "Operatie"])
    ws1.append(["WVWZZZ1KZAW000123", "B001TST", "2026-06-10", "123456", "OP-1"])
    ws2 = wb.create_sheet("Mai")
    ws2.append(["VIN", "Nr inmatriculare", "Data prestatie", "Odometru final", "Operatie"])
    ws2.append(["WVWZZZ1KZAW000999", "B009TST", "2026-05-10", "55000", "OP-1"])
    buf = io.BytesIO()
    wb.save(buf)
    return buf.getvalue()


def test_upload_slim_pe_un_rand(client):
    """Cand contul are trimiteri, bara de upload e compacta ('Importa:'), fara hero-ul mare."""
    _seed_submission()
    r = client.get("/?tab=acasa")
    assert r.status_code == 200
    html = r.text
    assert "Importa:" in html, "bara slim ('Importa:') lipseste cand contul are trimiteri"
    assert "Primul fisier" not in html, "hero-ul mare nu ar trebui sa apara pentru un cont cu trimiteri"


def test_first_run_pastreaza_hero(client):
    """First-run (zero trimiteri): hero-ul 'Primul fisier?' este pastrat."""
    r = client.get("/?tab=acasa")
    assert r.status_code == 200
    assert "Primul fisier" in r.text


def test_upload_pastreaza_drag_drop_si_input(client):
    """Input file ascuns + handler drag-drop raman functionale (JS refolosit)."""
    r = client.get("/_import/reset")
    assert r.status_code == 200
    html = r.text
    assert 'id="file-input"' in html
    assert 'id="drop-zone"' in html
    assert "dragover" in html and "drop" in html


def test_upload_pastreaza_select_foaie(client):
    """Cazul multi-sheet inca apare: selectorul de foaie e prezent."""
    data = _multi_sheet_xlsx()
    r = client.post(
        "/_import/upload",
        files={"file": ("multi.xlsx", io.BytesIO(data), "application/octet-stream")},
    )
    assert r.status_code == 200, r.text
    assert 'name="sheet_name"' in r.text
