from __future__ import annotations

from contextlib import closing
from dataclasses import dataclass
import hashlib
import json
import math
import os
from pathlib import Path
import sqlite3
from threading import Lock
import time


class RateLimitStoreError(RuntimeError):
    pass


@dataclass(frozen=True)
class RateLimitDecision:
    allowed: bool
    retry_after_seconds: int = 0
    capacity_exhausted: bool = False


class SQLiteRateLimitStore:
    """Small cross-process sliding-window store for security rate limits."""

    def __init__(
        self,
        path: Path,
        *,
        max_keys: int = 10_000,
        busy_timeout_ms: int = 1_000,
    ) -> None:
        self.path = path
        self.max_keys = max(1, max_keys)
        self.busy_timeout_ms = max(50, min(10_000, busy_timeout_ms))
        self._initialize_lock = Lock()
        self._initialized = False

    def initialize(self) -> None:
        with self._initialize_lock:
            if self._initialized and self.path.is_file():
                return
            try:
                self.path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
                file_descriptor = os.open(
                    self.path,
                    os.O_RDWR | os.O_CREAT,
                    0o600,
                )
                os.close(file_descriptor)
                if os.name == "posix":
                    self.path.chmod(0o600)
                with closing(self._connect()) as connection:
                    connection.execute("PRAGMA journal_mode=WAL")
                    connection.execute("PRAGMA synchronous=NORMAL")
                    connection.execute(
                        """
                        CREATE TABLE IF NOT EXISTS rate_limit_entries (
                            key_hash TEXT PRIMARY KEY,
                            hits_json TEXT NOT NULL,
                            updated_at REAL NOT NULL,
                            expires_at REAL NOT NULL
                        )
                        """
                    )
                    connection.execute(
                        """
                        CREATE INDEX IF NOT EXISTS ix_rate_limit_entries_expires_at
                        ON rate_limit_entries (expires_at)
                        """
                    )
                    connection.execute("PRAGMA user_version=1")
            except (OSError, sqlite3.Error) as exc:
                raise RateLimitStoreError(
                    "Nao foi possivel inicializar o armazenamento global de limites."
                ) from exc
            self._initialized = True

    def consume(
        self,
        key: str,
        *,
        limit: int,
        window_seconds: int,
        now: float | None = None,
    ) -> RateLimitDecision:
        if limit <= 0 or window_seconds <= 0:
            return RateLimitDecision(allowed=True)

        self.initialize()
        current_time = time.time() if now is None else float(now)
        if not math.isfinite(current_time):
            raise ValueError("O instante do limitador deve ser finito.")
        key_hash = hashlib.sha256(key.encode("utf-8")).hexdigest()
        cutoff = current_time - window_seconds

        connection: sqlite3.Connection | None = None
        try:
            connection = self._connect()
            connection.execute("BEGIN IMMEDIATE")
            row = connection.execute(
                "SELECT hits_json FROM rate_limit_entries WHERE key_hash = ?",
                (key_hash,),
            ).fetchone()
            hits = self._decode_hits(row[0]) if row is not None else []
            hits = sorted(timestamp for timestamp in hits if timestamp > cutoff)

            if not hits and row is not None:
                connection.execute(
                    "DELETE FROM rate_limit_entries WHERE key_hash = ?",
                    (key_hash,),
                )
                row = None

            if len(hits) >= limit:
                retry_after = max(
                    1,
                    min(window_seconds, math.ceil(hits[0] + window_seconds - current_time)),
                )
                connection.commit()
                return RateLimitDecision(
                    allowed=False,
                    retry_after_seconds=retry_after,
                )

            if row is None:
                connection.execute(
                    "DELETE FROM rate_limit_entries WHERE expires_at <= ?",
                    (current_time,),
                )
                entry_count = int(
                    connection.execute(
                        "SELECT COUNT(*) FROM rate_limit_entries"
                    ).fetchone()[0]
                )
                if entry_count >= self.max_keys:
                    connection.commit()
                    return RateLimitDecision(
                        allowed=False,
                        retry_after_seconds=min(window_seconds, 60),
                        capacity_exhausted=True,
                    )

            hits.append(current_time)
            self._write_entry(
                connection,
                key_hash,
                hits,
                current_time,
                current_time + window_seconds,
            )
            connection.commit()
            return RateLimitDecision(allowed=True)
        except (OSError, sqlite3.Error, TypeError, ValueError) as exc:
            if connection is not None:
                try:
                    connection.rollback()
                except sqlite3.Error:
                    pass
            raise RateLimitStoreError(
                "Falha ao consultar o armazenamento global de limites."
            ) from exc
        finally:
            if connection is not None:
                connection.close()

    def clear(self) -> None:
        self.initialize()
        try:
            with closing(self._connect()) as connection:
                connection.execute("DELETE FROM rate_limit_entries")
        except sqlite3.Error as exc:
            raise RateLimitStoreError("Falha ao limpar os limites globais.") from exc

    def entry_count(self) -> int:
        self.initialize()
        try:
            with closing(self._connect()) as connection:
                return int(
                    connection.execute(
                        "SELECT COUNT(*) FROM rate_limit_entries"
                    ).fetchone()[0]
                )
        except sqlite3.Error as exc:
            raise RateLimitStoreError("Falha ao contar os limites globais.") from exc

    def stored_keys(self) -> list[str]:
        self.initialize()
        try:
            with closing(self._connect()) as connection:
                return [
                    str(row[0])
                    for row in connection.execute(
                        "SELECT key_hash FROM rate_limit_entries ORDER BY key_hash"
                    ).fetchall()
                ]
        except sqlite3.Error as exc:
            raise RateLimitStoreError("Falha ao inspecionar os limites globais.") from exc

    def _connect(self) -> sqlite3.Connection:
        connection = sqlite3.connect(
            self.path,
            timeout=self.busy_timeout_ms / 1_000,
            isolation_level=None,
        )
        connection.execute(f"PRAGMA busy_timeout={self.busy_timeout_ms}")
        return connection

    @staticmethod
    def _decode_hits(value: str) -> list[float]:
        decoded = json.loads(value)
        if not isinstance(decoded, list) or len(decoded) > 10_000:
            raise ValueError("Estado invalido do limitador.")
        hits = [float(item) for item in decoded]
        if not all(math.isfinite(item) for item in hits):
            raise ValueError("Estado invalido do limitador.")
        return hits

    @staticmethod
    def _write_entry(
        connection: sqlite3.Connection,
        key_hash: str,
        hits: list[float],
        updated_at: float,
        expires_at: float,
    ) -> None:
        connection.execute(
            """
            INSERT INTO rate_limit_entries (key_hash, hits_json, updated_at, expires_at)
            VALUES (?, ?, ?, ?)
            ON CONFLICT(key_hash) DO UPDATE SET
                hits_json = excluded.hits_json,
                updated_at = excluded.updated_at,
                expires_at = excluded.expires_at
            """,
            (
                key_hash,
                json.dumps(hits, separators=(",", ":")),
                updated_at,
                expires_at,
            ),
        )
