"""Robustete selectie tinta chips: doar operatii nemapate IDENTIFICABILE (cu
cod_op_service) pot deveni tinta. Un item fara cod_op_service (chip liber, fara
nicio operatie asociata) nu are cum sa fie afisat ca tinta in template (chip-ul
warning se randeaza doar cand cod_op_service e truthy) — daca ar fi ales tinta,
ar deveni invizibil: userul nu vede niciun highlight, dar selectul tot arata
sugestii/NEDECLARAT pentru un "cui" pe care nu-l poate vedea.
"""

from __future__ import annotations

import os
import tempfile

import pytest


@pytest.fixture()
def conn(monkeypatch):
    tmp = tempfile.mkdtemp()
    monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "t.db"))
    from app.config import get_settings
    get_settings.cache_clear()
    from app.db import get_connection, init_db
    init_db()
    c = get_connection()
    yield c
    c.close()
    get_settings.cache_clear()


def _seed_cod(conn, cod: str, nume: str) -> None:
    conn.execute(
        "INSERT OR REPLACE INTO nomenclator_rar (cod_prestatie, nume_prestatie) VALUES (?, ?)",
        (cod, nume),
    )
    conn.commit()


def test_item_fara_cod_op_service_nu_devine_tinta(conn):
    """Chip liber (fara cod_op_service) nemapat nu poate fi tinta — e invizibil in template."""
    from app.web.routes import _chips_target_si_sugestii
    _seed_cod(conn, "OE-1", "Schimb ulei")
    from app.mapping import load_nomenclator
    nomenclator = load_nomenclator(conn)

    chips = [{"cod_prestatie": "", "cod_op_service": "", "denumire": "", "exclus": 0}]
    target_index, sugestii = _chips_target_si_sugestii(conn, chips, nomenclator)

    assert target_index is None
    assert sugestii == []


def test_operatie_identificabila_ramane_tinta(conn):
    """Regresie: o operatie nemapata cu cod_op_service ramane tinta normal."""
    from app.web.routes import _chips_target_si_sugestii
    _seed_cod(conn, "OE-1", "Schimb ulei motor")
    from app.mapping import load_nomenclator
    nomenclator = load_nomenclator(conn)

    chips = [{"cod_prestatie": "", "cod_op_service": "Op-A", "denumire": "Schimb ulei motor", "exclus": 0}]
    target_index, sugestii = _chips_target_si_sugestii(conn, chips, nomenclator)

    assert target_index == 0
    assert any(s.get("cod_prestatie") == "OE-1" for s in sugestii)


def test_sugestii_pentru_tinta_fara_denumire_intoarce_gol():
    """Denumire (si cod_op_service) goala pe tinta -> lista goala, fara sugestii irelevante."""
    from app.web.routes import _sugestii_select_pentru_tinta

    class _FakeConn:
        pass

    nomenclator = [{"cod_prestatie": "OE-1", "nume_prestatie": "Schimb ulei"}]
    out = _sugestii_select_pentru_tinta(_FakeConn(), "", nomenclator)
    assert out == []
    out_none = _sugestii_select_pentru_tinta(_FakeConn(), None, nomenclator)
    assert out_none == []
