#!/usr/bin/env python3
"""Listeaza prezentarile finalizate la RAR (verificare end-to-end: au ajuns?).

Face login cu credentialele din settings.xml (blocul <test> sau <production>,
in functie de AUTOPASS_RAR_ENV) si afiseaza ce e inregistrat la RAR. Folosit ca
sa confirmi ca prezentarile trimise de worker au ajuns efectiv: compari
`id_prezentare` din coada locala (status='sent') cu `id`-urile de aici.

Utilizare:
    AUTOPASS_RAR_ENV=test python3 -m tools.rar_finalizate
    ./start.sh test finalizate
"""

from __future__ import annotations

import sys
import xml.etree.ElementTree as ET

from app.config import ROOT, get_settings
from app.rar_client import RarClient, RarError


def _creds_for_env(env: str) -> dict | None:
    """Citeste credentialele pentru mediu (<test> / <production>) din settings.xml."""
    path = ROOT / "settings.xml"
    if not path.exists():
        return None
    block = "production" if env == "prod" else "test"
    try:
        root = ET.parse(path).getroot()
        node = root.find(f"./{block}/credentials")
        if node is None:
            return None
        email = (node.findtext("email") or "").strip()
        password = (node.findtext("password") or "").strip()
        if not email or not password or email.startswith("EMAIL_"):
            return None
        return {"email": email, "password": password}
    except ET.ParseError:
        return None


def main() -> int:
    settings = get_settings()
    env = settings.rar_env
    creds = _creds_for_env(env)
    if not creds:
        print(
            f"Lipsesc credentialele <{'production' if env == 'prod' else 'test'}> in settings.xml.\n"
            "Copiaza settings.xml.example -> settings.xml si completeaza-le.",
            file=sys.stderr,
        )
        return 2

    print(f"[finalizate] login RAR ({env}) ca {creds['email']} ...")
    rar = RarClient(settings)
    try:
        token = rar.login(creds["email"], creds["password"])
        items = rar.get_finalizate(token)
    except RarError as exc:
        print(f"[finalizate] eroare RAR: {exc}", file=sys.stderr)
        return 1
    finally:
        rar.close()

    if not items:
        print("[finalizate] RAR nu a intors nicio prezentare finalizata.")
        return 0

    print(f"[finalizate] {len(items)} prezentari inregistrate la RAR:\n")
    print(f"{'id':>8}  {'VIN':<18} {'data':<12} {'odometru':>10}")
    print("-" * 54)
    for it in items:
        idp = it.get("id", "")
        vin = (it.get("vin") or it.get("serieSasiu") or "")[:18]
        data = it.get("dataPrestatie") or ""
        odo = it.get("odometruFinal") or it.get("odometru") or ""
        print(f"{str(idp):>8}  {vin:<18} {str(data):<12} {str(odo):>10}")
    return 0


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