# scoring/metadata.py

from typing import Any, List
from pathlib import Path
from .base import BaseScorer, ScoreResult


class MetadataScorer(BaseScorer):
    def __init__(
        self,
        filename_weight: float = 0.3,
        path_weight: float = 0.2,
        extension_weight: float = 0.1,
        test_penalty: float = 0.2,
        max_depth_penalty: float = 0.3,
    ):
        super().__init__(weight=1.0)  # FIX 1: Call parent __init__
        self.filename_weight = filename_weight
        self.path_weight = path_weight
        self.extension_weight = extension_weight
        self.test_penalty = test_penalty
        self.max_depth_penalty = max_depth_penalty

    def _tokenize(self, text: str) -> List[str]:
        return [t for t in text.lower().split() if t]

    def score(self, query: str, chunk: Any) -> ScoreResult:  # FIX 2: chunk: Any (not Dict)
        # FIX 3: chunk is SemanticChunk object, use getattr() not .get()
        score = 0.0
        details = {}

        query_tokens = self._tokenize(query)

        # FIX 4: Get file_path from chunk object
        file_path_str = getattr(chunk, "file_path", "") or ""
        file_path_str = file_path_str.lower()

        # FIX 5: Extract filename from path
        try:
            filename = Path(file_path_str).stem.lower()
        except Exception:
            filename = ""

        # FIX 6: Get extension from path
        try:
            extension = Path(file_path_str).suffix.lower().lstrip(".")
        except Exception:
            extension = ""

        # --- Filename Boost ---
        filename_matches = sum(token in filename for token in query_tokens)
        if filename_matches:
            boost = filename_matches * self.filename_weight
            score += boost
            details["filename_boost"] = boost

        # --- Path Boost ---
        path_matches = sum(token in file_path_str for token in query_tokens)
        if path_matches:
            boost = path_matches * self.path_weight
            score += boost
            details["path_boost"] = boost

        # --- Extension Boost ---
        if extension and any(extension in token for token in query_tokens):
            score += self.extension_weight
            details["extension_boost"] = self.extension_weight

        # --- Test Penalty ---
        if "test" in filename or "test" in file_path_str:
            score -= self.test_penalty
            details["test_penalty"] = -self.test_penalty

        # --- Depth Penalty ---
        # FIX 7: Get depth from hierarchy object
        hierarchy = getattr(chunk, "hierarchy", None)
        depth = getattr(hierarchy, "depth", 0) if hierarchy else 0
        
        depth_penalty = min(depth * 0.05, self.max_depth_penalty)
        score -= depth_penalty
        details["depth_penalty"] = -depth_penalty

        final_score = max(score, 0.0)

        return ScoreResult(
            score=final_score,
            details=details
        )