"""Bounded idempotency state for streamed chat requests.

Clients may retry the same POST after a transport reset. When a request carries
``request_id``, the server must not execute its tools twice: completed streams
are replayed, active/uncertain duplicates are rejected, and all state is
TTL/capacity/byte/chunk bounded.
"""

from __future__ import annotations

import hashlib
import threading
import time
from collections import OrderedDict
from dataclasses import dataclass, field

from app.config import settings


@dataclass(frozen=True)
class ReplayDecision:
    status: str
    key: str | None = None
    generation: int = 0
    chunks: tuple[str, ...] = ()


@dataclass
class _ReplayEntry:
    generation: int
    request_fingerprint: str | None = None
    status: str = "in_flight"
    chunks: list[str] = field(default_factory=list)
    response_bytes: int = 0
    replayable: bool = True
    updated_at: float = field(default_factory=time.monotonic)


class RequestReplayStore:
    """Thread-safe bounded request replay store with conservative failures."""

    def __init__(
        self,
        *,
        ttl_seconds: float = 7200.0,
        max_entries: int = 1024,
        max_response_bytes: int = 4 * 1024 * 1024,
        max_total_response_bytes: int = 64 * 1024 * 1024,
        max_chunks: int = 20000,
    ) -> None:
        self._ttl_seconds = max(60.0, float(ttl_seconds))
        self._max_entries = max(1, int(max_entries))
        self._max_response_bytes = max(1024, int(max_response_bytes))
        self._max_total_response_bytes = max(1024, int(max_total_response_bytes))
        self._max_chunks = max(1, int(max_chunks))
        self._items: OrderedDict[str, _ReplayEntry] = OrderedDict()
        self._cached_response_bytes = 0
        self._lock = threading.RLock()
        self._generation = 0

    @staticmethod
    def _key(c_id: str | None, request_id: str | None) -> str | None:
        if not request_id:
            return None
        material = f"{c_id or ''}\0{request_id}".encode("utf-8", errors="replace")
        return hashlib.sha256(material).hexdigest()

    def _prune_locked(self, now: float) -> None:
        expired = [
            key for key, item in self._items.items()
            if item.status != "in_flight" and now - item.updated_at > self._ttl_seconds
        ]
        for key in expired:
            self._remove_locked(key)

    def _remove_locked(self, key: str) -> None:
        item = self._items.pop(key, None)
        if item is not None:
            self._cached_response_bytes -= item.response_bytes

    def _make_room_locked(self) -> bool:
        # Never evict an unexpired idempotency record: doing so would let the
        # old request_id execute its tools again. Capacity exhaustion must fail
        # closed until TTL cleanup frees a slot.
        return len(self._items) < self._max_entries

    def begin(
        self,
        c_id: str | None,
        request_id: str | None,
        request_fingerprint: str | None = None,
    ) -> ReplayDecision:
        key = self._key(c_id, request_id)
        if key is None:
            return ReplayDecision("untracked")
        now = time.monotonic()
        with self._lock:
            self._prune_locked(now)
            item = self._items.get(key)
            if item is not None:
                if item.request_fingerprint != request_fingerprint:
                    return ReplayDecision("payload_mismatch", key, item.generation)
                item.updated_at = now
                self._items.move_to_end(key)
                if item.status == "completed" and item.replayable:
                    return ReplayDecision(
                        "completed", key, item.generation, tuple(item.chunks),
                    )
                if item.status == "completed":
                    return ReplayDecision("unreplayable", key, item.generation)
                return ReplayDecision(item.status, key, item.generation)
            if not self._make_room_locked():
                return ReplayDecision("capacity")
            self._generation += 1
            item = _ReplayEntry(
                generation=self._generation,
                request_fingerprint=request_fingerprint,
                updated_at=now,
            )
            self._items[key] = item
            return ReplayDecision("new", key, item.generation)

    def append(self, decision: ReplayDecision, chunk: str) -> None:
        if decision.key is None or decision.status != "new":
            return
        encoded_size = len(chunk.encode("utf-8", errors="replace"))
        with self._lock:
            item = self._items.get(decision.key)
            if item is None or item.generation != decision.generation:
                return
            item.updated_at = time.monotonic()
            if not item.replayable:
                return
            exceeds_request_limit = (
                item.response_bytes + encoded_size > self._max_response_bytes
            )
            exceeds_store_limit = (
                self._cached_response_bytes + encoded_size
                > self._max_total_response_bytes
            )
            exceeds_chunk_limit = len(item.chunks) + 1 > self._max_chunks
            if exceeds_request_limit or exceeds_store_limit or exceeds_chunk_limit:
                item.replayable = False
                item.chunks.clear()
                self._cached_response_bytes -= item.response_bytes
                item.response_bytes = 0
                return
            item.chunks.append(chunk)
            item.response_bytes += encoded_size
            self._cached_response_bytes += encoded_size

    def read_chunks(self, decision: ReplayDecision) -> tuple[str, ...] | None:
        """Read the current response prefix while it is still replayable."""
        if decision.key is None:
            return ()
        with self._lock:
            item = self._items.get(decision.key)
            if item is None or item.generation != decision.generation or not item.replayable:
                return None
            return tuple(item.chunks)

    def complete(self, decision: ReplayDecision) -> None:
        self._set_status(decision, "completed")

    def mark_uncertain(self, decision: ReplayDecision) -> None:
        # A disconnected stream may still have running side effects; block
        # same-ID replay rather than risking a second tool execution.
        self._set_status(decision, "uncertain")

    def discard_unstarted(self, decision: ReplayDecision) -> None:
        if decision.key is None or decision.status != "new":
            return
        with self._lock:
            item = self._items.get(decision.key)
            if item is not None and item.generation == decision.generation:
                self._remove_locked(decision.key)

    def _set_status(self, decision: ReplayDecision, status: str) -> None:
        if decision.key is None or decision.status != "new":
            return
        with self._lock:
            item = self._items.get(decision.key)
            if item is None or item.generation != decision.generation:
                return
            item.status = status
            item.updated_at = time.monotonic()
            self._items.move_to_end(decision.key)

    def clear_all(self) -> None:
        with self._lock:
            self._items.clear()
            self._cached_response_bytes = 0

    def snapshot(self) -> dict[str, int]:
        """Return bounded operational counters without exposing request keys."""
        with self._lock:
            self._prune_locked(time.monotonic())
            return {
                "entries": len(self._items),
                "max_entries": self._max_entries,
                "in_flight": sum(
                    item.status == "in_flight" for item in self._items.values()
                ),
                "cached_response_bytes": self._cached_response_bytes,
                "max_total_response_bytes": self._max_total_response_bytes,
                "max_chunks": self._max_chunks,
            }


request_replay_store = RequestReplayStore(
    ttl_seconds=settings.request_replay_ttl_seconds,
    max_entries=settings.request_replay_max_entries,
    max_response_bytes=settings.request_replay_max_response_bytes,
    max_total_response_bytes=settings.request_replay_max_total_response_bytes,
    max_chunks=settings.request_replay_max_chunks,
)