"""Track how technical debt affects delivery velocity.

Records sprint velocity per module and correlates with debt scores
to show which modules are slowing down feature delivery.
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import Any

from ..store import DebtStore


@dataclass
class VelocityReport:
    """Velocity analysis for a module."""

    module: str
    avg_delivery_ratio: float  # delivered/planned (1.0 = 100%)
    trend: str  # "improving", "degrading", "stable"
    samples: int
    estimated_waste_pct: float  # % of capacity wasted on debt

    def to_dict(self) -> dict[str, Any]:
        return {
            "module": self.module,
            "avg_delivery_ratio": round(self.avg_delivery_ratio, 3),
            "trend": self.trend,
            "samples": self.samples,
            "estimated_waste_pct": round(self.estimated_waste_pct, 1),
        }


class VelocityTracker:
    """Track delivery velocity per module and correlate with debt."""

    def __init__(self, store: DebtStore) -> None:
        self.store = store

    def record_sprint(
        self,
        repo_path: str,
        module: str,
        sprint: str,
        planned_points: float,
        delivered_points: float,
    ) -> None:
        """Record sprint velocity for a module."""
        self.store.record_velocity(
            repo_path=repo_path,
            module=module,
            sprint=sprint,
            planned_points=planned_points,
            delivered_points=delivered_points,
        )

    def analyze_module(
        self, repo_path: str, module: str
    ) -> VelocityReport:
        """Analyze velocity trend for a module."""
        samples = self.store.get_velocity_for_module(repo_path, module)

        if not samples:
            return VelocityReport(
                module=module,
                avg_delivery_ratio=1.0,
                trend="insufficient_data",
                samples=0,
                estimated_waste_pct=0.0,
            )

        ratios: list[float] = []
        for s in samples:
            planned = s["planned_points"]
            delivered = s["delivered_points"]
            if planned > 0:
                ratios.append(delivered / planned)

        if not ratios:
            return VelocityReport(
                module=module,
                avg_delivery_ratio=1.0,
                trend="insufficient_data",
                samples=len(samples),
                estimated_waste_pct=0.0,
            )

        avg_ratio = sum(ratios) / len(ratios)

        # Trend: compare first half vs second half
        mid = len(ratios) // 2
        if mid > 0:
            first_avg = sum(ratios[:mid]) / mid
            second_avg = sum(ratios[mid:]) / len(ratios[mid:])
            diff = second_avg - first_avg
            if diff > 0.05:
                trend = "improving"
            elif diff < -0.05:
                trend = "degrading"
            else:
                trend = "stable"
        else:
            trend = "insufficient_data"

        # Waste: how much capacity is lost
        waste_pct = max(0.0, (1.0 - avg_ratio) * 100.0)

        return VelocityReport(
            module=module,
            avg_delivery_ratio=avg_ratio,
            trend=trend,
            samples=len(samples),
            estimated_waste_pct=waste_pct,
        )

    def analyze_all_modules(
        self, repo_path: str, modules: list[str]
    ) -> list[VelocityReport]:
        """Analyze velocity for multiple modules."""
        reports = [self.analyze_module(repo_path, m) for m in modules]
        reports.sort(key=lambda r: r.estimated_waste_pct, reverse=True)
        return reports
