"""Pattern: rolling summary.

When the conversation exceeds a budget, fold the oldest turns into a running
summary and keep only recent turns verbatim. The summarizer is any callable
`(previous_summary, messages) -> new_summary`; in production that is an LLM
call (see SUMMARY_PROMPT). The default is a crude extractive summarizer so the
pattern runs offline and deterministically in tests.
"""
from __future__ import annotations

import re
from typing import Callable

from .tokens import count_tokens

SUMMARY_PROMPT = """You maintain the running summary of a conversation between a user and an assistant.

Current summary:
{summary}

New messages to fold in:
{messages}

Write the updated summary in at most {max_words} words. Keep: decisions made, facts the
user stated about themselves or their project, open questions, and commitments. Drop:
greetings, repetition, and details that were later corrected. Use plain sentences."""

Summarizer = Callable[[str, list[dict]], str]


def naive_summarizer(previous: str, messages: list[dict], max_chars: int = 1200) -> str:
    """Keep the first sentence of each message. Deterministic, offline, lossy."""
    parts = [previous.strip()] if previous.strip() else []
    for m in messages:
        text = str(m.get("content", "")).strip()
        if not text:
            continue
        first = re.split(r"(?<=[.!?])\s", text, maxsplit=1)[0]
        parts.append(f"{m['role']}: {first}")
    summary = " ".join(parts)
    return summary[-max_chars:]


class RollingSummary:
    def __init__(self, max_tokens: int, keep_recent: int = 6,
                 summarizer: Summarizer = naive_summarizer,
                 counter: Callable[[str], int] = count_tokens):
        self.max_tokens = max_tokens
        self.keep_recent = keep_recent
        self.summarizer = summarizer
        self.counter = counter
        self.summary = ""
        self.recent: list[dict] = []
        self.folds = 0

    def _tokens(self) -> int:
        return self.counter(self.summary) + sum(self.counter(str(m["content"])) for m in self.recent)

    def add(self, role: str, content: str) -> None:
        self.recent.append({"role": role, "content": content})
        if self._tokens() > self.max_tokens and len(self.recent) > self.keep_recent:
            old = self.recent[:-self.keep_recent]
            self.recent = self.recent[-self.keep_recent:]
            self.summary = self.summarizer(self.summary, old)
            self.folds += 1

    def messages(self) -> list[dict]:
        out = []
        if self.summary:
            out.append({"role": "system", "content": f"Summary of earlier conversation: {self.summary}"})
        return out + list(self.recent)
