from collections import defaultdict

from .models import ClassificationResult, Classification
from .rules import DEFAULT_RULES
from .utils import unique_preserve_order


class ClassificationEngine:
    def __init__(self, rules=None):
        self.rules = rules or DEFAULT_RULES

    def classify(self, candidate):
        scores = defaultdict(int)
        reasons = []
        tags = []
        matched = []

        for rule in self.rules:
            results = rule(candidate)
            for result in results:
                scores[result.classification] += result.score
                reasons.extend(result.reasons)
                tags.extend(result.tags)
                matched.append(result.rule_name)

        if not scores:
            return ClassificationResult(
                candidate=candidate,
                classification=Classification.UNKNOWN,
                confidence=0.0,
                score=0,
                reasons=["No rules matched"],
                tags=["unknown"],
                matched_rules=[],
                score_breakdown={},
            )

        classification, score = max(scores.items(), key=lambda item: item[1])

        total_score = sum(scores.values())
        confidence = score / total_score if total_score else 0.0

        return ClassificationResult(
            candidate=candidate,
            classification=classification,
            confidence=round(confidence, 2),
            score=score,
            reasons=reasons,
            tags=unique_preserve_order(tags),
            matched_rules=unique_preserve_order(matched),
            score_breakdown={cls.value: value for cls, value in scores.items()},
        )
