import re
from collections import Counter

from home_agent.contracts.types import Item, ItemKind, MemoryRuleCandidate

_TOKEN = re.compile(r"[a-z]{4,}")


class ScopedMemoryEngine:
    def extract_candidates(self, important_items: list[Item]) -> list[MemoryRuleCandidate]:
        email_items = [item for item in important_items if item.kind == ItemKind.EMAIL]
        if not email_items:
            return []

        token_counts: Counter[str] = Counter()
        for item in email_items:
            token_counts.update(_TOKEN.findall(item.subject.lower()))

        candidates: list[MemoryRuleCandidate] = []
        for token, count in token_counts.most_common(5):
            if count < 2:
                continue
            confidence = min(0.95, 0.5 + (count / max(3, len(email_items))))
            candidates.append(
                MemoryRuleCandidate(
                    rule_key=f"subject_token:{token}",
                    description=f"Prioritize items containing token '{token}'",
                    evidence_count=count,
                    confidence=confidence,
                )
            )
        return candidates

    def apply_active_rules(self, active_rule_keys: set[str], item: Item) -> list[str]:
        reasons: list[str] = []
        for key in active_rule_keys:
            if key.startswith("subject_token:"):
                token = key.split(":", 1)[1]
                if token in item.subject.lower():
                    reasons.append(f"memory:{key}")
        return reasons
