from __future__ import annotations

from nees.types import MemoryItem, NEESRequest


class MemorySelector:
    def select(self, request: NEESRequest, limit: int = 3) -> list[MemoryItem]:
        message_terms = {
            token.strip(".,!?").lower()
            for token in request.message.split()
            if len(token.strip(".,!?")) > 2
        }

        scored: list[MemoryItem] = []
        for idx, item in enumerate(reversed(request.history)):
            content_terms = {
                token.strip(".,!?").lower()
                for token in item.content.split()
                if len(token.strip(".,!?")) > 2
            }
            overlap = len(message_terms & content_terms)
            recency_bonus = max(0.0, 0.3 - (idx * 0.05))
            score = overlap + recency_bonus
            if score <= 0:
                continue
            scored.append(
                MemoryItem(
                    content=item.content,
                    score=round(score, 3),
                    source=f"history:{item.role}",
                )
            )

        scored.sort(key=lambda item: item.score, reverse=True)
        return scored[:limit]
