#!/usr/bin/env python3
"""CLI carantina randuri tinute — atenuare hazard de rollback (PRD 5.19 Riscul R4).

Daca se face revert pe cod DUPA ce randuri au primit `held=1`, worker-ul pierde
filtrul `AND held=0` din `claim_one` -> ar trimite TOATE randurile tinute la RAR
(FINALIZATA e IREVERSIBILA). Acest helper carantineaza randurile tinute INAINTE
de un asemenea revert: le scoate din coada (`queued` -> `error`) cu mesajul
`ROLLBACK_QUARANTINE`, ca sa nu poata fi preluate de un worker fara filtrul held.

Adminul ruleaza pe masina gateway — nicio suprafata HTTP. Vezi runbook-ul
`docs/runbook-rollback-5.19.md` pentru procedura completa (inainte/dupa revert).

Utilizare:
    python -m tools.carantina_held            # carantineaza (scrie)
    python -m tools.carantina_held --dry-run  # doar numara, NU scrie
"""

from __future__ import annotations

import argparse
import sqlite3
import sys

from app.db import get_connection, init_db

# Randurile vizate: tinute manual, inca in coada. `sending`/`sent` NU se ating
# (FINALIZATA e terminal la RAR), iar `error`/`needs_*` nu pleaca oricum.
_WHERE = "held=1 AND status='queued'"


def _count(conn: sqlite3.Connection) -> int:
    return int(conn.execute(f"SELECT COUNT(*) AS n FROM submissions WHERE {_WHERE}").fetchone()["n"])


def carantina(conn: sqlite3.Connection, dry_run: bool = False) -> int:
    """Carantineaza randurile tinute. Intoarce numarul de randuri afectate.

    Cu `dry_run=True` doar numara (nu modifica nimic).

    Seteaza si `purge_after` (retentia randurilor blocate, `blocked_retention_days`): fara
    el un rand `error` iesit din `queued` NU primeste niciodata purge_after -> PII criptat
    ar sta la nesfarsit (`purge_expired` sterge doar randuri cu purge_after setat). Aliniat
    cu calea normala worker `error` (/code-review #4).
    """
    n = _count(conn)
    if dry_run or n == 0:
        return n
    from app.config import get_settings
    days = int(get_settings().blocked_retention_days)
    conn.execute(
        "UPDATE submissions SET status='error', rar_error='ROLLBACK_QUARANTINE', "
        f"purge_after=datetime('now', '+{days} days'), updated_at=datetime('now') WHERE {_WHERE}"
    )
    return n


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(
        description="Carantineaza randurile tinute (queued AND held=1) inainte de un revert de cod (PRD 5.19 R4)."
    )
    parser.add_argument(
        "--dry-run", action="store_true",
        help="doar numara randurile tinute, fara sa scrie in DB"
    )
    args = parser.parse_args(argv)

    init_db()  # asigura schema (submissions.held)
    conn = get_connection()
    try:
        n = carantina(conn, dry_run=args.dry_run)
    finally:
        conn.close()

    if args.dry_run:
        print(f"[dry-run] {n} randuri tinute (queued AND held=1) ar fi carantinate. Nimic scris.")
    elif n == 0:
        print("Niciun rand tinut de carantinat (queued AND held=1).")
    else:
        print(f"{n} randuri carantinate: status='error', rar_error='ROLLBACK_QUARANTINE'.")
    return 0


if __name__ == "__main__":
    sys.exit(main())
