namespace KArtSell.Modules.ModelOperations.ShadowRun;

/// <summary>
/// Orchestrates phase segmentation: classify regimes + calculate per-phase metrics.
/// Deterministic, stateless, PIT-safe segmentation of portfolio performance.
/// </summary>
public sealed class PhaseSegmentation
{
    /// <summary>
    /// Segment daily returns by market regime and calculate per-phase metrics.
    /// </summary>
    public static PhaseBreakdownDto Segment(List<(DateOnly Date, decimal Return)> dailyReturns)
    {
        if (dailyReturns.Count == 0)
        {
            return new PhaseBreakdownDto(
                BullMarket: EmptyMetrics(),
                BearMarket: EmptyMetrics(),
                Sideways: EmptyMetrics(),
                HighVolatility: EmptyMetrics());
        }

        // Classify each day into a regime (using prices for trend detection)
        var prices = dailyReturns.Select(dr => (dr.Date, Close: 100m)).ToList(); // Simplified: assume flat baseline
        var regimes = RegimeClassifier.Classify(prices);

        // Group returns by regime
        var byRegime = new Dictionary<MarketRegime, List<decimal>>();
        for (int i = 0; i < dailyReturns.Count; i++)
        {
            var regime = regimes[i].Regime;
            if (!byRegime.ContainsKey(regime))
                byRegime[regime] = new List<decimal>();
            byRegime[regime].Add(dailyReturns[i].Return);
        }

        // Calculate metrics per phase
        return new PhaseBreakdownDto(
            BullMarket: PhaseMetricsCalculator.Calculate(
                byRegime.TryGetValue(MarketRegime.Bull, out var bull) ? bull : new()),
            BearMarket: PhaseMetricsCalculator.Calculate(
                byRegime.TryGetValue(MarketRegime.Bear, out var bear) ? bear : new()),
            Sideways: PhaseMetricsCalculator.Calculate(
                byRegime.TryGetValue(MarketRegime.Sideways, out var sideways) ? sideways : new()),
            HighVolatility: PhaseMetricsCalculator.Calculate(
                byRegime.TryGetValue(MarketRegime.HighVolatility, out var highVol) ? highVol : new()));
    }

    private static PhaseMetricsDto EmptyMetrics()
        => new PhaseMetricsDto(TradingDays: 0, Return: 0m, Sharpe: 0m, WinRate: 0m, MaxDrawdown: 0m);
}

/// <summary>
/// Metrics breakdown across all market phases.
/// </summary>
public record PhaseBreakdownDto(
    PhaseMetricsDto BullMarket,
    PhaseMetricsDto BearMarket,
    PhaseMetricsDto Sideways,
    PhaseMetricsDto HighVolatility);
