"""Inventory report generator.

Produces stock level change metrics, trend analysis, and outlier
detection from inventory 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."""
    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_stock, previous_stock, daily_counts):
    """Generate an inventory report with change, trend, and outlier analysis."""
    change = _percentage_change(previous_stock, current_stock)
    trend = _moving_average(daily_counts)
    outliers = _detect_outliers(daily_counts)
    return {
        "type": "inventory",
        "change": MetricResult(change, "Stock Change %", "up" if change > 0 else "down"),
        "trend": trend,
        "outliers": outliers,
        "summary": f"Stock {'increased' if change > 0 else 'decreased'} by {abs(change):.1f}%",
    }
