"""Sales report generator.

Produces revenue change metrics, trend analysis, and outlier
detection from sales data. Calculations are implemented inline
for this report's specific requirements.
"""

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=3):
    """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 generate(current_sales, previous_sales, daily_data):
    """Generate a sales report with change, trend, and outlier analysis."""
    change = _percentage_change(previous_sales, current_sales)
    trend = _moving_average(daily_data)
    outliers = _detect_outliers(daily_data)
    return {
        "type": "sales",
        "change": MetricResult(change, "Revenue Change %", "up" if change > 0 else "down"),
        "trend": trend,
        "outliers": outliers,
        "summary": f"Sales {'increased' if change > 0 else 'decreased'} by {abs(change):.1f}%",
    }
