"""Clipboard history — tracks recent clipboard entries for AI context injection."""

from __future__ import annotations

import logging
import time
from collections import deque
from typing import TypedDict

log = logging.getLogger(__name__)


class ClipboardEntry(TypedDict):
    """Type definition for clipboard entry."""

    text: str
    timestamp: float
    time: str


class ClipboardHistory:
    """Track recent clipboard entries and provide them as AI context.

    Used to inject recent clipboard content as background context
    when processing text, giving the AI more information about
    what the user has been working with.
    """

    __slots__ = ("_entries", "_last_text")

    def __init__(self, max_entries: int = 10) -> None:
        self._entries: deque[ClipboardEntry] = deque(maxlen=max_entries)
        self._last_text: str = ""

    def add(self, text: str) -> None:
        """Add a new clipboard entry if it differs from the last one."""
        text = (text or "").strip()
        if not text or text == self._last_text:
            return
        self._last_text = text
        entry: ClipboardEntry = {
            "text": text,
            "timestamp": time.time(),
            "time": time.strftime("%H:%M:%S"),
        }
        self._entries.append(entry)
        log.debug("Clipboard history: added entry (%d total)", len(self._entries))

    def get_recent(self, n: int = 5) -> list[ClipboardEntry]:
        """Get the N most recent clipboard entries (oldest first)."""
        items = list(self._entries)
        return items[-n:] if len(items) > n else items

    def get_context_string(self, n: int = 3, max_chars: int = 500) -> str:
        """Format recent clipboard entries as context string for AI.

        Returns empty string if no entries. Each entry is truncated
        to max_chars characters.
        """
        entries = self.get_recent(n)
        if not entries:
            return ""
        lines = ["[Recent clipboard context:]"]
        for entry in entries:
            preview = entry["text"][:max_chars]
            if len(entry["text"]) > max_chars:
                preview += "..."
            lines.append(f"- [{entry['time']}] {preview}")
        return "\n".join(lines)

    def clear(self) -> None:
        """Clear all clipboard history."""
        self._entries.clear()
        self._last_text = ""

    @property
    def count(self) -> int:
        return len(self._entries)

    @property
    def last_text(self) -> str:
        return self._last_text
