"""Teste PRD 5.19 US-007 — gauge-uri /metrics pentru coada tinuta.

/metrics expune, pe langa `autopass_submissions{status=...}`, doua gauge-uri
DERIVATE (zero stare noua), scoped global:
  - autopass_held_submissions          = COUNT(queued AND held=1)
  - autopass_held_oldest_age_seconds   = varsta (s) a celui mai vechi rand tinut

TDD: fixtura izoleaza DB per test (pattern din test_worker_held.py).
"""

from __future__ import annotations

import json
import os
import tempfile

import pytest
from fastapi.testclient import TestClient


@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()


def _client():
    from app.main import app
    return TestClient(app)


_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, created_at=None):
    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),
    )
    sid = int(cur.lastrowid)
    if created_at is not None:
        conn.execute("UPDATE submissions SET created_at=? WHERE id=?", (created_at, sid))
    return sid


def _metric(text, name):
    for line in text.splitlines():
        if line.startswith(name + " "):
            return line[len(name) + 1:].strip()
    return None


def test_held_gauges_numara_si_varsta(env):
    conn = env
    # doua randuri tinute (unul vechi de ~10 zile) + unul ne-tinut
    _insert(conn, status="queued", held=1, created_at="2026-06-25 00:00:00")
    _insert(conn, status="queued", held=1)
    _insert(conn, status="queued", held=0)

    body = _client().get("/metrics").text
    assert _metric(body, "autopass_held_submissions") == "2"
    oldest = int(_metric(body, "autopass_held_oldest_age_seconds"))
    assert oldest > 0


def test_held_gauge_zero_fara_randuri_tinute(env):
    conn = env
    _insert(conn, status="queued", held=0)
    _insert(conn, status="sent", held=0)

    body = _client().get("/metrics").text
    assert _metric(body, "autopass_held_submissions") == "0"
    # varsta = 0 cand nu exista randuri tinute (COALESCE)
    assert _metric(body, "autopass_held_oldest_age_seconds") == "0"


def test_held_gauge_ignora_tinut_ne_queued(env):
    conn = env
    # held=1 dar status != queued (ex. deja carantinat) NU se numara
    _insert(conn, status="error", held=1)
    _insert(conn, status="queued", held=1)

    body = _client().get("/metrics").text
    assert _metric(body, "autopass_held_submissions") == "1"
