"""Teste US-007 (PRD 5.10): afisare operatie de service in detaliu.

Cand payload-ul contine `cod_op_service` (codul intern al service-ului), detaliul
trebuie sa afiseze „Operatie service" (cod + denumire), distinct de „Operatie RAR".
Cand lipseste (a venit direct cu `cod_prestatie`), randul nu apare deloc — conventie
"" (string gol) stabilita de US-002 in payload_view.py.

Apare atat in contextul editabil (needs_data/needs_mapping) cat si read-only (sent/error).
"""

from __future__ import annotations

import json
import os
import re
import tempfile

import pytest
from starlette.testclient import TestClient


def _create_account_user(email: str, name: str = "Service", password: str = "parolasecreta10"):
    from app.accounts import create_account
    from app.users import create_user
    from app.db import get_connection

    conn = get_connection()
    try:
        acct_id = create_account(conn, name, active=True)
        create_user(conn, acct_id, email, password)
        return acct_id
    finally:
        conn.close()


def _login(client, email: str, password: str = "parolasecreta10") -> None:
    resp = client.get("/login")
    m = re.search(r'name="csrf_token"\s+value="([^"]+)"', resp.text) or \
        re.search(r'value="([^"]+)"\s+name="csrf_token"', resp.text)
    assert m
    resp = client.post(
        "/login",
        data={"email": email, "parola": password, "csrf_token": m.group(1)},
    )
    assert resp.status_code == 303


def _insert(acct: int, *, status: str, payload: dict) -> int:
    from app.db import get_connection
    conn = get_connection()
    try:
        cur = conn.execute(
            "INSERT INTO submissions (idempotency_key, account_id, status, payload_json) VALUES (?, ?, ?, ?)",
            (f"k-{os.urandom(6).hex()}", acct, status, json.dumps(payload)),
        )
        conn.commit()
        return int(cur.lastrowid)
    finally:
        conn.close()


def _payload_cu_op_service(vin: str = "WVWZZZ1JZXW000001") -> dict:
    """Payload cu cod_op_service + denumire (vine prin API cu cod intern)."""
    return {
        "vin": vin,
        "nr_inmatriculare": "B100TST",
        "data_prestatie": "2026-06-20",
        "odometru_final": "50000",
        "prestatii": [
            {
                "cod_op_service": "OP-FRANE-77",
                "denumire": "Verificare si reglaj frane",
                "cod_prestatie": "OE-1",  # mapat deja
            }
        ],
    }


def _payload_fara_op_service(vin: str = "WVWZZZ1JZXW000002") -> dict:
    """Payload cu cod_prestatie direct (fara cod_op_service)."""
    return {
        "vin": vin,
        "nr_inmatriculare": "B200TST",
        "data_prestatie": "2026-06-20",
        "odometru_final": "50000",
        "prestatii": [{"cod_prestatie": "OE-1"}],
    }


@pytest.fixture()
def client(monkeypatch):
    tmp = tempfile.mkdtemp()
    monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "op_service_test.db"))
    monkeypatch.setenv("AUTOPASS_WEB_AUTH_REQUIRED", "true")
    from app.config import get_settings
    get_settings.cache_clear()
    from app.web import ratelimit
    ratelimit._hits.clear()
    from app.main import app
    with TestClient(app, follow_redirects=False) as c:
        yield c
    ratelimit._hits.clear()
    get_settings.cache_clear()


def test_detaliu_arata_operatie_service_read_only(client):
    """In context read-only (sent), operatia de service (cod intern + denumire) apare distinct.

    Randul „Operatie service" trebuie sa fie vizibil si sa contina codul intern
    si denumirea venita prin API, separat de „Operatie RAR".
    """
    acct = _create_account_user("op_srv_ro@test.com")
    sid = _insert(acct, status="sent", payload=_payload_cu_op_service())
    _login(client, "op_srv_ro@test.com")

    resp = client.get(f"/_fragments/trimitere/{sid}")
    assert resp.status_code == 200
    html = resp.text

    # Codul intern de service trebuie sa apara
    assert "OP-FRANE-77" in html, (
        "Codul intern al operatiei de service (op_service_cod) trebuie afisat in detaliu read-only."
    )
    # Denumirea trebuie sa apara
    assert "Verificare si reglaj frane" in html, (
        "Denumirea operatiei de service (op_service_denumire) trebuie afisata in detaliu read-only."
    )
    # Eticheta „Operatie service" trebuie sa apara
    assert "Operatie service" in html, (
        "Eticheta 'Operatie service' trebuie sa apara in detaliu read-only."
    )


def test_detaliu_arata_operatie_service_editabil(client):
    """In context editabil (needs_data), operatia de service apare de asemenea.

    Campul este read-only in forma (nu e editabil de operator), dar trebuie afisat
    ca referinta pentru ce a cerut service-ul.
    """
    acct = _create_account_user("op_srv_edit@test.com")
    sid = _insert(acct, status="needs_data", payload=_payload_cu_op_service())
    _login(client, "op_srv_edit@test.com")

    resp = client.get(f"/_fragments/trimitere/{sid}")
    assert resp.status_code == 200
    html = resp.text

    # Codul intern trebuie sa apara si in editare
    assert "OP-FRANE-77" in html, (
        "Codul intern al operatiei de service trebuie afisat si in contextul editabil (needs_data)."
    )
    # Eticheta trebuie sa apara
    assert "Operatie service" in html, (
        "Eticheta 'Operatie service' trebuie sa apara si in contextul editabil."
    )


def test_detaliu_omite_cand_lipseste_read_only(client):
    """Cand payload-ul nu are cod_op_service (vine direct cu cod_prestatie), randul nu apare.

    Conventie US-002: op_service_cod = "" (nu "—"). Randul lipseste complet
    (nu apare „Operatie service: —" sau rand gol).
    """
    acct = _create_account_user("op_srv_absent_ro@test.com")
    sid = _insert(acct, status="sent", payload=_payload_fara_op_service())
    _login(client, "op_srv_absent_ro@test.com")

    resp = client.get(f"/_fragments/trimitere/{sid}")
    assert resp.status_code == 200
    html = resp.text

    # Eticheta „Operatie service" nu trebuie sa apara cand lipseste
    assert "Operatie service" not in html, (
        "Randul 'Operatie service' nu trebuie sa apara cand payload-ul nu contine cod_op_service. "
        "Conventie US-002: op_service_cod='' → rand absent complet."
    )


def test_detaliu_omite_cand_lipseste_editabil(client):
    """Cand payload-ul nu are cod_op_service, randul nu apare nici in editare."""
    acct = _create_account_user("op_srv_absent_edit@test.com")
    sid = _insert(acct, status="needs_data", payload=_payload_fara_op_service())
    _login(client, "op_srv_absent_edit@test.com")

    resp = client.get(f"/_fragments/trimitere/{sid}")
    assert resp.status_code == 200
    html = resp.text

    assert "Operatie service" not in html, (
        "Randul 'Operatie service' nu trebuie sa apara in editare cand lipseste cod_op_service."
    )
