"""
Pure helpers for StatisticalAnalyzer (entropy, HHI, recency weight, confidence).
"""

import math
from typing import Dict, Any, Optional

from .constants import (
    RECENCY_WEIGHT_7_DAYS,
    RECENCY_WEIGHT_30_DAYS,
    RECENCY_WEIGHT_60_DAYS,
    RECENCY_WEIGHT_OLDER,
    CONFIDENCE_NORMALIZER,
    CONFIDENCE_HHI_OFFSET,
    CONFIDENCE_HHI_FACTOR,
)


def entropy_from_counts(counts: Dict[str, int], total: int) -> float:
    """Shannon entropy (base 2). total = sum(counts.values())."""
    if total <= 0 or not counts:
        return 0.0
    ent = 0.0
    for count in counts.values():
        if count <= 0:
            continue
        p = count / total
        ent -= p * math.log2(p)
    return round(ent, 2)


def hhi_from_counts(counts: Dict[Any, int], _total: int) -> float:
    """Herfindahl-Hirschman Index. Uses only strictly positive counts; denominator is their sum."""
    if not counts:
        return 0.0
    positives = [c for c in counts.values() if c > 0]
    t = sum(positives)
    if t <= 0:
        return 0.0
    return round(sum((c / t) ** 2 for c in positives), 2)


def weighted_recency(last_order_days_ago: Optional[int]) -> float:
    """Recency decay weight from last order days ago."""
    if last_order_days_ago is None:
        return 0.0
    if last_order_days_ago <= 7:
        return RECENCY_WEIGHT_7_DAYS
    if last_order_days_ago <= 30:
        return RECENCY_WEIGHT_30_DAYS
    if last_order_days_ago <= 60:
        return RECENCY_WEIGHT_60_DAYS
    return RECENCY_WEIGHT_OLDER


def math_confidence(total_orders: int, restaurant_hhi: float) -> float:
    """Normalized confidence from order count and HHI."""
    if total_orders <= 0:
        return 0.0
    raw = math.log1p(total_orders) * (CONFIDENCE_HHI_OFFSET + (restaurant_hhi * CONFIDENCE_HHI_FACTOR))
    return round(min(1.0, raw / CONFIDENCE_NORMALIZER), 2)
