import json
import os
import fcntl
import tempfile
from pathlib import Path

class AttemptStore:
    def __init__(self, ruta):
        self.path = Path(ruta)
        self.lock_path = Path(str(ruta) + ".lock")

    def registrar(self, clave, intento, momento):
        self.lock_path.parent.mkdir(
            parents=True, exist_ok=True
        )

        with open(self.lock_path, "a+") as lock:
            fcntl.flock(lock, fcntl.LOCK_EX)

            try:
                if self.path.exists():
                    datos = json.loads(
                        self.path.read_text(encoding="utf-8")
                    )
                else:
                    datos = {}

                registros = datos.setdefault(clave, [])

                if any(
                    r.get("attempt") == intento
                    for r in registros
                ):
                    return False

                registros.append({
                    "attempt": intento,
                    "time": momento
                })

                fd, temporal = tempfile.mkstemp(
                    dir=str(self.path.parent),
                    prefix=self.path.name + "."
                )

                try:
                    with os.fdopen(fd, "w", encoding="utf-8") as f:
                        json.dump(datos, f, indent=2)
                        f.flush()
                        os.fsync(f.fileno())

                    os.replace(temporal, self.path)

                finally:
                    if os.path.exists(temporal):
                        os.unlink(temporal)

                return True

            finally:
                fcntl.flock(lock, fcntl.LOCK_UN)
