"""Error Pattern Repository — in-memory store for error patterns."""

from __future__ import annotations

from cleveragents.domain.models.core.error_pattern import ErrorPattern


class ErrorPatternRepository:
    """In-memory CRUD + pattern-matching repository for error patterns."""

    def __init__(self) -> None:
        self._patterns: dict[str, ErrorPattern] = {}

    def create(self, pattern: ErrorPattern) -> ErrorPattern:
        """Create a new error pattern."""
        self._patterns[pattern.pattern_id] = pattern
        return pattern

    def get(self, pattern_id: str) -> ErrorPattern | None:
        """Get a pattern by ID."""
        return self._patterns.get(pattern_id)

    def list_all(self) -> list[ErrorPattern]:
        """List all patterns, sorted by last_seen descending."""
        return sorted(self._patterns.values(), key=lambda p: p.last_seen, reverse=True)

    def update(self, pattern: ErrorPattern) -> ErrorPattern:
        """Update an existing pattern."""
        self._patterns[pattern.pattern_id] = pattern
        return pattern

    def delete(self, pattern_id: str) -> bool:
        """Delete a pattern by ID. Returns True if deleted."""
        return self._patterns.pop(pattern_id, None) is not None

    def match_context(self, context_text: str) -> list[ErrorPattern]:
        """Find patterns whose keywords appear in the context text."""
        context_lower = context_text.lower()
        matched: list[ErrorPattern] = []
        for pattern in self._patterns.values():
            if pattern.keywords:
                if any(kw.lower() in context_lower for kw in pattern.keywords):
                    matched.append(pattern)
            else:
                # Fallback: check if pattern description appears in context
                if pattern.pattern.lower() in context_lower:
                    matched.append(pattern)
        return sorted(matched, key=lambda p: p.frequency, reverse=True)

    def count(self) -> int:
        """Return the number of patterns stored."""
        return len(self._patterns)

    def statistics(self) -> dict[str, int | float]:
        """Return aggregate statistics about stored patterns."""
        patterns = self.list_all()
        total = len(patterns)
        total_freq = sum(p.frequency for p in patterns)
        return {
            "total_patterns": total,
            "total_occurrences": total_freq,
            "avg_frequency": total_freq / total if total > 0 else 0.0,
        }
