"""Teste PRD 5.19 R4 — tools/carantina_held.py (atenuare hazard de rollback).

Carantineaza randurile `queued AND held=1` (-> `error`/`ROLLBACK_QUARANTINE`)
ca sa nu fie trimise de un worker fara filtrul `AND held=0` dupa un revert.
`--dry-run` doar numara, fara sa scrie.
"""

from __future__ import annotations

import json
import os
import tempfile

import pytest


@pytest.fixture()
def env(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()
    conn = get_connection()
    yield conn
    conn.close()
    get_settings.cache_clear()


_CONTENT = {
    "vin": "WVWZZZ1KZAW000123", "nr_inmatriculare": "B999TST",
    "data_prestatie": "2026-06-15", "odometru_final": "123456",
    "prestatii": [{"cod_prestatie": "OE-1"}],
}


def _insert(conn, status="queued", held=0):
    cur = conn.execute(
        "INSERT INTO submissions (idempotency_key, status, payload_json, account_id, held) "
        "VALUES (?, ?, ?, ?, ?)",
        (f"key-{os.urandom(4).hex()}", status, json.dumps(_CONTENT), 1, held),
    )
    return int(cur.lastrowid)


def _row(conn, sid):
    return conn.execute("SELECT * FROM submissions WHERE id=?", (sid,)).fetchone()


def _run(argv):
    from tools.carantina_held import main
    return main(argv)


def test_carantineaza_rand_tinut(env, capsys):
    conn = env
    sid = _insert(conn, status="queued", held=1)
    rc = _run([])
    out = capsys.readouterr().out
    assert rc == 0
    assert "1 randuri carantinate" in out
    r = _row(conn, sid)
    assert r["status"] == "error"
    assert r["rar_error"] == "ROLLBACK_QUARANTINE"
    # /code-review #4: randul carantinat primeste purge_after (altfel PII ar sta la nesfarsit,
    # purge_expired sterge doar randuri cu purge_after setat).
    assert r["purge_after"] is not None
    assert conn.execute(
        "SELECT purge_after > datetime('now') AS ok FROM submissions WHERE id=?", (sid,)
    ).fetchone()["ok"] == 1


def test_dry_run_nu_modifica(env, capsys):
    conn = env
    sid = _insert(conn, status="queued", held=1)
    rc = _run(["--dry-run"])
    out = capsys.readouterr().out
    assert rc == 0
    assert "dry-run" in out
    assert "1 randuri" in out
    r = _row(conn, sid)
    assert r["status"] == "queued"  # neschimbat
    assert r["rar_error"] is None


def test_nu_atinge_randuri_ne_tinute_sau_ne_queued(env, capsys):
    conn = env
    sid_libera = _insert(conn, status="queued", held=0)
    sid_sent = _insert(conn, status="sent", held=1)  # held dar deja plecat
    sid_tinuta = _insert(conn, status="queued", held=1)
    rc = _run([])
    capsys.readouterr()
    assert rc == 0
    assert _row(conn, sid_libera)["status"] == "queued"
    assert _row(conn, sid_sent)["status"] == "sent"
    assert _row(conn, sid_tinuta)["status"] == "error"


def test_fara_randuri_tinute(env, capsys):
    _insert(env, status="queued", held=0)
    rc = _run([])
    out = capsys.readouterr().out
    assert rc == 0
    assert "Niciun rand tinut" in out
