"""US-001: Schema + persistenta reguli text de mapare (operation_text_rules).

Teste RED-first: verifica tabela, functiile de persistenta si unicitatea per cont.
"""

from __future__ import annotations

import os
import tempfile

import pytest


# --------------------------------------------------------------------------- #
# Fixtures                                                                    #
# --------------------------------------------------------------------------- #

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


@pytest.fixture()
def conn(env):
    from app.db import get_connection
    c = get_connection()
    yield c
    c.close()


# --------------------------------------------------------------------------- #
# Teste                                                                       #
# --------------------------------------------------------------------------- #

def test_save_text_rule_persista(conn):
    """save_text_rule insereaza un rand; load_text_rules il returneaza."""
    from app.mapping import save_text_rule, load_text_rules

    save_text_rule(conn, account_id=1, pattern="verificare", cod_prestatie="OE-2", auto_send=False)
    conn.commit()

    rules = load_text_rules(conn, account_id=1)
    assert len(rules) == 1
    r = rules[0]
    assert r["pattern"] == "verificare"
    assert r["cod_prestatie"] == "OE-2"
    assert r["auto_send"] == 0
    assert r["priority"] == 0


def test_load_text_rules_per_cont(conn):
    """load_text_rules returneaza DOAR regulile contului dat, nu ale altor conturi."""
    from app.mapping import save_text_rule, load_text_rules

    # Creeaza un cont suplimentar (id=2)
    conn.execute("INSERT INTO accounts (id, name) VALUES (2, 'cont2')")
    conn.commit()

    save_text_rule(conn, account_id=1, pattern="revizie", cod_prestatie="OE-1", auto_send=False)
    save_text_rule(conn, account_id=2, pattern="vopsitorie", cod_prestatie="OE-3", auto_send=False)
    conn.commit()

    rules1 = load_text_rules(conn, account_id=1)
    rules2 = load_text_rules(conn, account_id=2)

    assert len(rules1) == 1
    assert rules1[0]["pattern"] == "revizie"
    assert len(rules2) == 1
    assert rules2[0]["pattern"] == "vopsitorie"


def test_delete_text_rule(conn):
    """delete_text_rule sterge regula specificata; load_text_rules returneaza lista vida."""
    from app.mapping import save_text_rule, load_text_rules, delete_text_rule

    save_text_rule(conn, account_id=1, pattern="schimb ulei", cod_prestatie="OE-2", auto_send=True)
    conn.commit()

    assert len(load_text_rules(conn, account_id=1)) == 1

    delete_text_rule(conn, account_id=1, pattern="schimb ulei")
    conn.commit()

    assert load_text_rules(conn, account_id=1) == []


def test_unic_per_cont_pattern(conn):
    """save_text_rule face upsert: al doilea apel cu acelasi (account_id, pattern)
    actualizeaza cod_prestatie si auto_send, nu creeaza un rand nou."""
    from app.mapping import save_text_rule, load_text_rules

    save_text_rule(conn, account_id=1, pattern="inspectie", cod_prestatie="OE-1", auto_send=False)
    conn.commit()

    # Al doilea apel = upsert: schimba codul si auto_send
    save_text_rule(conn, account_id=1, pattern="inspectie", cod_prestatie="OE-2", auto_send=True)
    conn.commit()

    rules = load_text_rules(conn, account_id=1)
    assert len(rules) == 1  # nu s-a dublat
    assert rules[0]["cod_prestatie"] == "OE-2"
    assert rules[0]["auto_send"] == 1


def test_load_text_rules_ordine(conn):
    """load_text_rules returneaza regulile ordonate priority ASC, id ASC."""
    from app.mapping import save_text_rule, load_text_rules

    # Inseram direct cu priority diferit ca sa testam ordinea
    conn.execute(
        "INSERT INTO operation_text_rules (account_id, pattern, cod_prestatie, auto_send, priority) "
        "VALUES (1, 'gamma', 'OE-3', 0, 10)"
    )
    conn.execute(
        "INSERT INTO operation_text_rules (account_id, pattern, cod_prestatie, auto_send, priority) "
        "VALUES (1, 'alfa', 'OE-1', 0, 0)"
    )
    conn.execute(
        "INSERT INTO operation_text_rules (account_id, pattern, cod_prestatie, auto_send, priority) "
        "VALUES (1, 'beta', 'OE-2', 0, 0)"
    )
    conn.commit()

    rules = load_text_rules(conn, account_id=1)
    # priority 0 inainte de priority 10; la egalitate de priority: id ASC (alfa < beta < gamma)
    assert rules[0]["pattern"] == "alfa"
    assert rules[1]["pattern"] == "beta"
    assert rules[2]["pattern"] == "gamma"


def test_account_or_default_none_equals_1(conn):
    """load_text_rules cu account_id=None aplica account_or_default -> returneaza regulile contului 1."""
    from app.mapping import save_text_rule, load_text_rules

    save_text_rule(conn, account_id=None, pattern="reparatie", cod_prestatie="OE-1", auto_send=False)
    conn.commit()

    rules = load_text_rules(conn, account_id=None)
    assert len(rules) == 1
    assert rules[0]["pattern"] == "reparatie"
