/**
 * Flow Trend Detector
 * Tracks net premium changes over rolling windows to determine if flow is SURGING, FADING, or STABLE
 */

/**
 * Detect flow trend for a ticker
 * @param {Array} flows - Array of flow records for a ticker (sorted by time desc, most recent first)
 * @returns {Object} Flow trend analysis
 */
export function detectFlowTrend(flows) {
  if (!flows || flows.length === 0) {
    return {
      trend: 'NO_DATA',
      status: '💀 DEAD',
      lastFlowMinutesAgo: null,
      netPremiumChange: 0,
      netPremiumCurrent: 0,
      netPremium15mAgo: null,
      netPremium30mAgo: null,
      message: 'No flow data available'
    };
  }

  const now = new Date();
  const mostRecentFlow = flows[0];
  const flowTimestamp = new Date(mostRecentFlow.flow_ts_utc || mostRecentFlow.CreatedDate || now);
  const minutesAgo = Math.floor((now - flowTimestamp) / (1000 * 60));

  // Calculate net premium for current flow
  const netPremiumCurrent = (mostRecentFlow.bull_total || 0) - (mostRecentFlow.bear_total || 0);

  // Get flows from 15 and 30 minutes ago
  const fifteenMinutesAgo = new Date(now.getTime() - 15 * 60 * 1000);
  const thirtyMinutesAgo = new Date(now.getTime() - 30 * 60 * 1000);

  // Find flows closest to 15min and 30min ago
  let flow15m = null;
  let flow30m = null;
  let minDiff15m = Infinity;
  let minDiff30m = Infinity;

  for (const flow of flows) {
    const flowTime = new Date(flow.flow_ts_utc || flow.CreatedDate || 0);
    const diff15m = Math.abs(flowTime - fifteenMinutesAgo);
    const diff30m = Math.abs(flowTime - thirtyMinutesAgo);

    if (diff15m < minDiff15m && flowTime <= fifteenMinutesAgo) {
      minDiff15m = diff15m;
      flow15m = flow;
    }
    if (diff30m < minDiff30m && flowTime <= thirtyMinutesAgo) {
      minDiff30m = diff30m;
      flow30m = flow;
    }
  }

  // Calculate net premiums at different time points
  const netPremium15mAgo = flow15m 
    ? (flow15m.bull_total || 0) - (flow15m.bear_total || 0)
    : null;
  const netPremium30mAgo = flow30m
    ? (flow30m.bull_total || 0) - (flow30m.bear_total || 0)
    : null;

  // Determine trend
  let trend = 'STABLE';
  let status = '🟡 STABLE';
  let message = 'Flow holding steady';

  // If no flow in 60+ minutes, it's DEAD
  if (minutesAgo >= 60) {
    trend = 'DEAD';
    status = '💀 DEAD';
    message = `No new flow in ${minutesAgo} minutes - signal stale`;
    return {
      trend,
      status,
      lastFlowMinutesAgo: minutesAgo,
      netPremiumChange: 0,
      netPremiumCurrent,
      netPremium15mAgo,
      netPremium30mAgo,
      message
    };
  }

  // Calculate trend based on net premium changes
  if (netPremium15mAgo !== null && netPremium30mAgo !== null) {
    // Compare current vs 15min ago vs 30min ago
    const change15m = netPremiumCurrent - netPremium15mAgo;
    const change30m = netPremiumCurrent - netPremium30mAgo;
    const change15to30 = netPremium15mAgo - netPremium30mAgo;

    // SURGING: Net premium increasing consistently
    if (change15m > 0 && change30m > 0 && change15to30 > 0) {
      // All three time points show increasing net premium
      trend = 'SURGING';
      status = '🔥 SURGING';
      message = 'Net premium increasing - institutions still buying';
    } else if (change15m > 0 && change30m > 0) {
      // Current > 15m > 30m (increasing)
      trend = 'SURGING';
      status = '🔥 SURGING';
      message = 'Net premium increasing - institutions still buying';
    } else if (change15m < 0 && change30m < 0 && change15to30 < 0) {
      // FADING: Net premium decreasing consistently
      trend = 'FADING';
      status = '⚠️ FADING';
      message = 'Net premium decreasing - institutions done, retail taking over';
    } else if (change15m < 0 && change30m < 0) {
      // Current < 15m < 30m (decreasing)
      trend = 'FADING';
      status = '⚠️ FADING';
      message = 'Net premium decreasing - institutions done, retail taking over';
    } else {
      // STABLE: Mixed or flat
      trend = 'STABLE';
      status = '🟡 STABLE';
      message = 'No significant change - holding pattern, wait for breakout';
    }
  } else if (netPremium15mAgo !== null) {
    // Only have 15min comparison
    const change15m = netPremiumCurrent - netPremium15mAgo;
    if (Math.abs(change15m) > 100000) { // Significant change threshold
      if (change15m > 0) {
        trend = 'SURGING';
        status = '🔥 SURGING';
        message = 'Net premium increasing in last 15min';
      } else {
        trend = 'FADING';
        status = '⚠️ FADING';
        message = 'Net premium decreasing in last 15min';
      }
    }
  }

  // Calculate total change
  const netPremiumChange = netPremium30mAgo !== null
    ? netPremiumCurrent - netPremium30mAgo
    : netPremium15mAgo !== null
    ? netPremiumCurrent - netPremium15mAgo
    : 0;

  // ADD: Volume spike detection
  const recentVolumes = flows.slice(0, 5).map(f => f.vol_num || f.Volume || 0).filter(v => v > 0);
  const avgVolume = recentVolumes.length > 0 
    ? recentVolumes.reduce((a, b) => a + b, 0) / recentVolumes.length 
    : 0;
  const currentVolume = mostRecentFlow.vol_num || mostRecentFlow.Volume || 0;
  const volumeSpike = avgVolume > 0 && currentVolume > avgVolume * 2; // 2x average = spike
  const volumeRatio = avgVolume > 0 ? currentVolume / avgVolume : 1;

  // ENHANCE: SURGING with volume spike = stronger signal
  if (trend === 'SURGING' && volumeSpike) {
    status = '🔥🔥 SURGING (VOL SPIKE)';
    message = 'Net premium increasing + volume spike = institutions aggressively buying';
  }

  return {
    trend,
    status,
    lastFlowMinutesAgo: minutesAgo,
    netPremiumChange,
    netPremiumCurrent,
    netPremium15mAgo,
    netPremium30mAgo,
    volumeSpike, // NEW
    volumeRatio, // NEW
    currentVolume, // NEW
    avgVolume, // NEW
    message
  };
}

/**
 * Batch detect flow trends for multiple tickers
 * @param {Object} tickerFlows - Object mapping ticker symbols to their flow arrays
 * @returns {Object} Flow trend analysis per ticker
 */
export function batchDetectFlowTrends(tickerFlows) {
  const results = {};

  for (const [ticker, flows] of Object.entries(tickerFlows)) {
    results[ticker] = detectFlowTrend(flows);
  }

  return results;
}

/**
 * Format flow trend for display
 */
export function formatFlowTrend(trend) {
  if (!trend) return { display: 'N/A', color: 'gray', icon: '⚪' };

  const colors = {
    'SURGING': 'green',
    'FADING': 'red',
    'STABLE': 'yellow',
    'DEAD': 'gray',
    'NO_DATA': 'gray'
  };

  const icons = {
    'SURGING': '🔥',
    'FADING': '⚠️',
    'STABLE': '🟡',
    'DEAD': '💀',
    'NO_DATA': '⚪'
  };

  const minutesText = trend.lastFlowMinutesAgo !== null
    ? `${trend.lastFlowMinutesAgo}min ago`
    : 'N/A';

  return {
    display: `${trend.status} | ${minutesText}`,
    color: colors[trend.trend] || 'gray',
    icon: icons[trend.trend] || '⚪',
    full: trend
  };
}

