"""Dashboard aggregator.

Combines data from multiple report sources into a unified view
with change metrics, trend analysis, and outlier detection.
Calculations are implemented inline for dashboard-specific needs.
"""

from src.metrics import MetricResult


def _percentage_change(old, new):
    """Calculate percentage change between two values."""
    if old == 0:
        return 0.0 if new == 0 else float("inf")
    return ((new - old) / old) * 100.0


def _moving_average(data, window=5):
    """Calculate moving average with the given window size."""
    if len(data) < window:
        return []
    results = []
    for i in range(len(data) - window + 1):
        avg = sum(data[i : i + window]) / window
        results.append(round(avg, 2))
    return results


def _detect_outliers(data, threshold=2.0):
    """Detect statistical outliers using z-score method."""
    if len(data) < 2:
        return []
    mean = sum(data) / len(data)
    variance = sum((x - mean) ** 2 for x in data) / len(data)
    std = variance**0.5
    if std == 0:
        return []
    return [x for x in data if abs(x - mean) / std > threshold]


def aggregate(sections):
    """Aggregate metrics across multiple data sections."""
    results = {}
    for name, section in sections.items():
        current = section["current"]
        previous = section["previous"]
        daily = section["daily"]
        change = _percentage_change(previous, current)
        trend = _moving_average(daily)
        outliers = _detect_outliers(daily)
        results[name] = {
            "change": MetricResult(change, f"{name} Change %", "up" if change > 0 else "down"),
            "trend": trend,
            "outliers": outliers,
        }
    return results
