"""Store de resultados de firma del xamiSDK.

Guarda el estado de cada operacion de firma por request_id: pendiente cuando se
envio el hash a Xami, y completado (con la ruta del PDF firmado) cuando llego el
sign.result por push y se ensamblo. El CLI en modo --wait consulta aqui.

Estados: PENDING -> DONE | ERROR
"""
from __future__ import annotations
import json
import os
import stat
import time


class Results:
    def __init__(self, base_dir: str):
        self.dir = os.path.join(base_dir, "results")
        os.makedirs(self.dir, exist_ok=True)

    def _path(self, request_id: str) -> str:
        return os.path.join(self.dir, f"{request_id}.json")

    def mark_pending(self, request_id: str, meta: dict | None = None):
        self._write(request_id, {"request_id": request_id, "status": "PENDING",
                                 "created_at": int(time.time()), "meta": meta or {}})

    def mark_done(self, request_id: str, output_path: str, extra: dict | None = None):
        rec = self.get(request_id) or {"request_id": request_id}
        rec.update({"status": "DONE", "output_path": output_path,
                    "done_at": int(time.time())})
        if extra:
            rec.update(extra)
        self._write(request_id, rec)

    def mark_error(self, request_id: str, error: str):
        rec = self.get(request_id) or {"request_id": request_id}
        rec.update({"status": "ERROR", "error": error, "done_at": int(time.time())})
        self._write(request_id, rec)

    def get(self, request_id: str) -> dict | None:
        p = self._path(request_id)
        if not os.path.exists(p):
            return None
        try:
            with open(p) as f:
                return json.load(f)
        except Exception:
            return None

    def list(self, limit: int = 50) -> list[dict]:
        items = []
        for name in os.listdir(self.dir):
            if name.endswith(".json"):
                d = self.get(name[:-5])
                if d:
                    items.append(d)
        items.sort(key=lambda x: x.get("created_at", 0), reverse=True)
        return items[:limit]

    def _write(self, request_id: str, rec: dict):
        p = self._path(request_id)
        with open(p, "w") as f:
            json.dump(rec, f, indent=2)
        os.chmod(p, stat.S_IRUSR | stat.S_IWUSR)
