"""
Confidence scorer for AI categorization predictions.

Computes a confidence_score (0.00–100.00) from a set of weighted evidence
signals and derives a confidence_level relative to the configured threshold.
"""

from typing import List, Dict, Any


def compute_score(evidence_signals: List[Dict[str, Any]]) -> float:
    """
    Compute a confidence score from a list of evidence signals.

    Each signal must have a 'weight' (0.0–1.0) and a 'signal_strength'
    (0.0–1.0) that indicates how strongly the signal supports the prediction.

    Returns a score in the range [10.00, 100.00].  The floor of 10 is applied
    when no usable evidence exists so predictions are never scored at zero.

    Args:
        evidence_signals: List of dicts, each with keys:
            - weight (float): relative importance of this signal (0.0–1.0)
            - signal_strength (float): how strongly it supports the category (0.0–1.0)

    Returns:
        float: confidence score in [10.00, 100.00]
    """
    if not evidence_signals:
        return 10.0

    total_weight = sum(s.get("weight", 0.0) for s in evidence_signals)
    if total_weight <= 0:
        return 10.0

    weighted_sum = sum(
        s.get("weight", 0.0) * s.get("signal_strength", 0.0)
        for s in evidence_signals
    )

    raw_score = (weighted_sum / total_weight) * 100.0
    score = max(10.0, min(100.0, round(raw_score, 2)))
    return score


def derive_level(score: float, threshold: float) -> str:
    """
    Derive a confidence level label from a numeric score.

    Args:
        score:     Confidence score in [0, 100].
        threshold: The configured auto-approval threshold (e.g., 90.0).

    Returns:
        'high'   if score >= threshold
        'medium' if score >= 70 and score < threshold
        'low'    if score < 70
    """
    if score >= threshold:
        return "high"
    if score >= 70.0:
        return "medium"
    return "low"
