"""
ChunkHive Keyword Scorer
=========================

Boosts chunks that contain exact keyword matches
in name, docstring, or code.
"""

import re
from typing import List
from .base import BaseScorer, ScoreResult


class KeywordScorer(BaseScorer):
    """
    Scores chunks based on keyword overlap.
    Useful for boosting exact matches alongside semantic similarity.
    """

    def __init__(self, weight: float = 0.3):
        super().__init__(weight)

    def _tokenize(self, text: str) -> List[str]:
        return re.findall(r"\b\w+\b", text.lower())

    def score(self, query: str, chunk) -> ScoreResult:

        query_tokens = set(self._tokenize(query))

        content_parts = []

        if chunk.ast.name:
            content_parts.append(chunk.ast.name)

        if chunk.ast.docstring:
            content_parts.append(chunk.ast.docstring)

        content_parts.append(chunk.code)

        content = " ".join(content_parts).lower()
        content_tokens = set(self._tokenize(content))

        if not query_tokens:
            return ScoreResult(score=0.0, details={})

        overlap = query_tokens.intersection(content_tokens)

        match_ratio = len(overlap) / len(query_tokens)

        weighted_score = match_ratio * self.weight

        return ScoreResult(
            score=weighted_score,
            details={
                "keyword_overlap": list(overlap),
                "match_ratio": match_ratio,
                "weight": self.weight
            }
        )
