/**
 * Feature Service
 * Extracts raw mathematical features from raw data to feed the scoring engine.
 */

/**
 * Calculate ATR as a percentage of the last close price.
 * ATR% = the real intraday "is this tradeable?" metric.
 * 
 * @param {Array} candles - Array of candle objects {high, low, close}, most recent last.
 * @param {number} period - Period for ATR calculation (default: 14)
 * @returns {number|null} ATR as a percentage (e.g. 5.8 means 5.8% average range)
 */
export function atrPercent(candles, period = 14) {
  if (!candles || candles.length <= period) return null;

  const trs = [];
  for (let i = 1; i < candles.length; i++) {
    const { high, low } = candles[i];
    const prevClose = candles[i - 1].close;
    
    // True Range
    trs.push(Math.max(
      high - low,
      Math.abs(high - prevClose),
      Math.abs(low - prevClose)
    ));
  }
  
  // Simple moving average of TRs for the last `period` days
  const recent = trs.slice(-period);
  const atr = recent.reduce((a, b) => a + b, 0) / recent.length;
  
  const lastClose = candles[candles.length - 1].close;
  if (!lastClose) return null;
  
  return (atr / lastClose) * 100;
}

/**
 * Extract Estimate Revisions (Up vs Down) direction.
 * If quoteSummary contains earningsTrend (from Yahoo Finance).
 * 
 * @param {Object} rawData - The raw data payload from Yahoo Finance
 * @returns {number} Score representing net revisions: positive = more up than down
 */
export function estimateRevisionsNet(rawData) {
  // If we don't have the raw earningsTrend array, return 0 (neutral)
  const trends = rawData?.quoteSummary?.result?.[0]?.earningsTrend?.trend;
  if (!trends || !Array.isArray(trends)) return 0;
  
  // We want to look at the current quarter (0q) or current year (0y)
  // Usually the first two elements are current qtr and next qtr
  let netUp = 0;
  
  for (const t of trends.slice(0, 2)) {
    const up = t?.earningsEstimate?.upLast30days?.raw || 0;
    const down = t?.earningsEstimate?.downLast30days?.raw || 0;
    netUp += (up - down);
  }
  
  return netUp;
}

/**
 * Calculates Relative Volume
 * @param {number} volume - Today's volume
 * @param {number} avgVolume10d - 10-day average volume
 * @param {number} avgVolume3m - 3-month average volume
 */
export function calculateRvol(volume, avgVolume10d, avgVolume3m) {
  if (!volume) return null;
  if (avgVolume10d) return volume / avgVolume10d;
  if (avgVolume3m) return volume / avgVolume3m;
  return null;
}
