"""
ChunkHive Structural Scorer
===========================

Boosts chunks based on structural importance.

Enhancements:
- Class > Method hierarchy boost
- Public API boost
- Entrypoint detection
- Decorator awareness
- Short utility boost
- Query-aware structural hints
"""

from typing import Any
from .base import BaseScorer, ScoreResult


class StructuralScorer(BaseScorer):
    """
    Scores chunks based on structural signals.
    """

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

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

        score = 0.0
        details = {}

        query_lower = query.lower()

        chunk_type = getattr(chunk, "chunk_type", None)
        ast_node = getattr(chunk, "ast", None)
        code = getattr(chunk, "code", "")

        # ----------------------------
        # 1️⃣ Query-aware boosting
        # ----------------------------
        if "class" in query_lower and chunk_type == "class":
            score += 1.0
            details["query_class_boost"] = 1.0

        if "function" in query_lower and chunk_type in ("function", "method"):
            score += 1.0
            details["query_function_boost"] = 1.0

        # ----------------------------
        # 2️⃣ Structural hierarchy
        # ----------------------------
        if chunk_type == "class":
            score += 0.4
            details["class_priority_boost"] = 0.4

        elif chunk_type == "method":
            score += 0.2
            details["method_priority_boost"] = 0.2

        # ----------------------------
        # 3️⃣ Public API boost
        # ----------------------------
        if ast_node and hasattr(ast_node, "name"):
            name = getattr(ast_node, "name", "")
            if name and not name.startswith("_"):
                score += 0.3
                details["public_api_boost"] = 0.3

            # Entrypoint detection
            if name == "__main__":
                score += 0.5
                details["entrypoint_boost"] = 0.5

        # ----------------------------
        # 4️⃣ Decorator awareness
        # ----------------------------
        if ast_node and hasattr(ast_node, "decorator_list"):
            decorators = getattr(ast_node, "decorator_list", [])
            if decorators:
                score += 0.2
                details["decorator_boost"] = 0.2

        # ----------------------------
        # 5️⃣ Short utility boost
        # ----------------------------
        if code:
            length = len(code)
            if length < 400:
                score += 0.2
                details["short_chunk_boost"] = 0.2

        weighted_score = score * self.weight

        return ScoreResult(
            score=weighted_score,
            details={
                "raw_structure_score": score,
                "weight": self.weight,
                **details,
            },
        )
