/**
 * Regime Service
 * Classifies the broad market state (fast, mechanical).
 */

/**
 * Classify Market Regime based on SPY, VIX, and Breadth
 * @param {Object} spyTechnicals - Technical data for SPY (needs close, sma_20, sma_50)
 * @param {number} vixClose - Latest close price of ^VIX
 * @param {number} breadthPctAbove50 - Percentage of universe stocks above their 50 SMA
 * @returns {Object} Regime classification
 */
export function classifyRegime(spyTechnicals, vixClose, breadthPctAbove50) {
  if (!spyTechnicals || vixClose == null || breadthPctAbove50 == null) {
    return { trend: 'neutral', vol: 'normal_vol', breadth: 'mixed', raw: {} };
  }

  // If we have candles, get the latest close. Otherwise fallback to current price if passed differently.
  const close = spyTechnicals.candles ? spyTechnicals.candles[spyTechnicals.candles.length - 1].close : 0;
  const sma20 = spyTechnicals.sma_20;
  const sma50 = spyTechnicals.sma_50;

  // Trend logic: mechanical
  const trend = (close > sma50 && sma20 > sma50) ? 'risk_on'
              : (close < sma50 && sma20 < sma50) ? 'risk_off'
              : 'neutral';

  // Volatility logic (VIX)
  const vol = vixClose > 25 ? 'high_vol' : vixClose < 15 ? 'low_vol' : 'normal_vol';

  // Breadth logic
  const breadth = breadthPctAbove50 > 60 ? 'broad'
                : breadthPctAbove50 < 40 ? 'narrow' : 'mixed';

  return {
    trend,
    vol,
    breadth,
    raw: {
      spy_close: close,
      spy_sma20: sma20,
      spy_sma50: sma50,
      vix: vixClose,
      breadthPctAbove50
    }
  };
}
