"""
Priority Scorer for Context Management.

Scores context based on assigned priority levels.
"""

from typing import Any, ClassVar

from ..types import BaseContext, ContextType
from .base import BaseScorer


class PriorityScorer(BaseScorer):
    """
    Scores context based on priority levels.

    Converts priority enum values to normalized scores.
    Also applies type-based priority bonuses.
    """

    # Default priority bonuses by context type
    DEFAULT_TYPE_BONUSES: ClassVar[dict[ContextType, float]] = {
        ContextType.SYSTEM: 0.2,  # System prompts get a boost
        ContextType.TASK: 0.15,  # Current task is important
        ContextType.TOOL: 0.1,  # Recent tool results matter
        ContextType.KNOWLEDGE: 0.0,  # Knowledge scored by relevance
        ContextType.CONVERSATION: 0.0,  # Conversation scored by recency
    }

    def __init__(
        self,
        weight: float = 1.0,
        type_bonuses: dict[ContextType, float] | None = None,
    ) -> None:
        """
        Initialize priority scorer.

        Args:
            weight: Scorer weight for composite scoring
            type_bonuses: Optional context-type priority bonuses
        """
        super().__init__(weight)
        self._type_bonuses = type_bonuses or self.DEFAULT_TYPE_BONUSES.copy()

    async def score(
        self,
        context: BaseContext,
        query: str,
        **kwargs: Any,
    ) -> float:
        """
        Score context based on priority.

        Args:
            context: Context to score
            query: Query (not used for priority, kept for interface)
            **kwargs: Additional parameters

        Returns:
            Priority score between 0.0 and 1.0
        """
        # Get base priority score
        priority_value = context.priority
        base_score = self._priority_to_score(priority_value)

        # Apply type bonus
        context_type = context.get_type()
        bonus = self._type_bonuses.get(context_type, 0.0)

        return self.normalize_score(base_score + bonus)

    def _priority_to_score(self, priority: int) -> float:
        """
        Convert priority value to normalized score.

        Priority values (from ContextPriority):
        - CRITICAL (100) -> 1.0
        - HIGH (80) -> 0.8
        - NORMAL (50) -> 0.5
        - LOW (20) -> 0.2
        - MINIMAL (0) -> 0.0

        Args:
            priority: Priority value (0-100)

        Returns:
            Normalized score (0.0-1.0)
        """
        # Clamp to valid range
        clamped = max(0, min(100, priority))
        return clamped / 100.0

    def get_type_bonus(self, context_type: ContextType) -> float:
        """
        Get priority bonus for a context type.

        Args:
            context_type: Context type

        Returns:
            Bonus value
        """
        return self._type_bonuses.get(context_type, 0.0)

    def set_type_bonus(self, context_type: ContextType, bonus: float) -> None:
        """
        Set priority bonus for a context type.

        Args:
            context_type: Context type
            bonus: Bonus value (0.0-1.0)
        """
        if not 0.0 <= bonus <= 1.0:
            raise ValueError("Bonus must be between 0.0 and 1.0")
        self._type_bonuses[context_type] = bonus

    async def score_batch(
        self,
        contexts: list[BaseContext],
        query: str,
        **kwargs: Any,
    ) -> list[float]:
        """
        Score multiple contexts.

        Args:
            contexts: Contexts to score
            query: Query (not used)
            **kwargs: Additional parameters

        Returns:
            List of scores (same order as input)
        """
        # Priority scoring is fast, no async needed
        return [await self.score(ctx, query, **kwargs) for ctx in contexts]
