"""Rolling transcript and screenshot buffers."""

from __future__ import annotations

import time
import threading
from collections import deque
from dataclasses import dataclass, field
from pathlib import Path
from typing import List, Optional


@dataclass
class TranscriptEntry:
    timestamp: float
    text: str


class RollingTranscriptBuffer:
    """Thread-safe rolling transcript buffer that evicts entries by age."""

    def __init__(self, max_minutes: int = 10) -> None:
        self._max_seconds = max_minutes * 60
        self._entries: deque[TranscriptEntry] = deque()
        self._lock = threading.Lock()

    def append(self, text: str) -> None:
        """Add a new transcript segment."""
        text = text.strip()
        if not text:
            return
        with self._lock:
            now = time.time()
            self._entries.append(TranscriptEntry(timestamp=now, text=text))
            # Evict expired entries
            cutoff = now - self._max_seconds
            while self._entries and self._entries[0].timestamp < cutoff:
                self._entries.popleft()

    def get_recent(self, minutes: Optional[int] = None) -> str:
        """Return joined text from the last N minutes (default: all buffered)."""
        with self._lock:
            if not self._entries:
                return ""
            if minutes is None:
                return "\n".join(e.text for e in self._entries)
            cutoff = time.time() - minutes * 60
            recent = [e.text for e in self._entries if e.timestamp >= cutoff]
            return "\n".join(recent)

    def clear(self) -> None:
        with self._lock:
            self._entries.clear()

    def __len__(self) -> int:
        with self._lock:
            return len(self._entries)


class ScreenshotBuffer:
    """Thread-safe buffer for screenshot file paths."""

    def __init__(self) -> None:
        self._paths: List[Path] = []
        self._lock = threading.Lock()

    def append(self, path: Path) -> None:
        with self._lock:
            self._paths.append(path)

    def pop_all(self) -> List[Path]:
        """Return all paths and clear the buffer atomically."""
        with self._lock:
            paths = list(self._paths)
            self._paths.clear()
            return paths

    def __len__(self) -> int:
        with self._lock:
            return len(self._paths)
