/**
 * Flow Decay Detector
 * Tracks when institutional flow stops and flags potential retail FOMO or distribution phases
 */

/**
 * Detect flow decay for a ticker
 * @param {Array} flows - Array of flow records for a ticker (sorted by time desc)
 * @param {Object} currentPrice - Current price data
 * @returns {Object} Flow decay analysis
 */
export function detectFlowDecay(flows, currentPrice = {}) {
  if (!flows || flows.length === 0) {
    return {
      status: 'NO_FLOW',
      lastFlowMinutesAgo: null,
      priceTrend: 'UNKNOWN',
      signal: 'NO_DATA',
      warning: null
    };
  }
  
  // Get most recent flow
  const mostRecentFlow = flows[0];
  const flowTimestamp = new Date(mostRecentFlow.flow_ts_utc || mostRecentFlow.CreatedDate || Date.now());
  const now = new Date();
  const minutesAgo = Math.floor((now - flowTimestamp) / (1000 * 60));
  
  // Determine price trend (simplified - would need actual price history)
  const priceTrend = determinePriceTrend(flows, currentPrice);
  
  // Flow decay thresholds
  const DECAY_THRESHOLD_MINUTES = 30;
  const STRONG_DECAY_THRESHOLD_MINUTES = 60;
  
  let status = 'ACTIVE';
  let signal = 'ACTIVE';
  let warning = null;
  
  if (minutesAgo >= STRONG_DECAY_THRESHOLD_MINUTES) {
    status = 'STRONG_DECAY';
    
    if (priceTrend === 'RISING') {
      signal = 'FADE';
      warning = '⚠️ FLOW DECAY: No new flow in 60+ minutes but price still rising = Retail FOMO phase = Fade opportunity';
    } else if (priceTrend === 'FALLING') {
      signal = 'AVOID';
      warning = '⚠️ FLOW DECAY: No new flow in 60+ minutes and price dropping = No one stepping in = Avoid catching falling knife';
    } else {
      signal = 'NEUTRAL';
      warning = 'Flow stopped but price stable - monitor for reversal';
    }
  } else if (minutesAgo >= DECAY_THRESHOLD_MINUTES) {
    status = 'DECAY';
    
    if (priceTrend === 'RISING') {
      signal = 'CAUTION';
      warning = '⚠️ Flow decay detected: No new flow in 30+ minutes but price still rising - potential retail FOMO';
    } else if (priceTrend === 'FALLING') {
      signal = 'CAUTION';
      warning = '⚠️ Flow decay detected: No new flow in 30+ minutes and price dropping - institutions may be done';
    } else {
      signal = 'MONITOR';
      warning = 'Flow slowing - monitor for continuation or reversal';
    }
  } else {
    status = 'ACTIVE';
    signal = 'ACTIVE';
    warning = null;
  }
  
  return {
    status,
    lastFlowMinutesAgo: minutesAgo,
    lastFlowTimestamp: flowTimestamp.toISOString(),
    priceTrend,
    signal,
    warning,
    rocketScore: mostRecentFlow.rocketScore || mostRecentFlow.rocket_score || 0,
    direction: mostRecentFlow.direction || 'UNKNOWN'
  };
}

/**
 * Determine price trend from flows and current price
 * Simplified version - ideally would use actual price history
 */
function determinePriceTrend(flows, currentPrice) {
  if (!currentPrice || !currentPrice.close) {
    return 'UNKNOWN';
  }
  
  // Try to infer from flow data if available
  if (flows.length >= 2) {
    const recent = flows[0];
    const older = flows[1];
    
    const recentPrice = recent.u_close || recent.spot_num || recent.Price;
    const olderPrice = older.u_close || older.spot_num || older.Price;
    
    if (recentPrice && olderPrice) {
      const change = ((recentPrice - olderPrice) / olderPrice) * 100;
      if (change > 0.5) return 'RISING';
      if (change < -0.5) return 'FALLING';
    }
  }
  
  // Fallback: use current price vs some reference
  // This is a simplified check - real implementation would need price history
  return 'UNKNOWN';
}

/**
 * Batch detect flow decay for multiple tickers
 * @param {Object} tickerFlows - Object mapping ticker symbols to their flow arrays
 * @param {Object} priceData - Object mapping ticker symbols to current price data
 * @returns {Object} Flow decay analysis per ticker
 */
export function batchDetectFlowDecay(tickerFlows, priceData = {}) {
  const results = {};
  
  for (const [ticker, flows] of Object.entries(tickerFlows)) {
    const currentPrice = priceData[ticker] || {};
    results[ticker] = detectFlowDecay(flows, currentPrice);
  }
  
  return results;
}

/**
 * Format flow decay for display
 */
export function formatFlowDecay(decay) {
  if (!decay) return { display: 'N/A', color: 'gray' };
  
  const statusIcons = {
    'ACTIVE': '🟢',
    'DECAY': '🟡',
    'STRONG_DECAY': '🔴',
    'NO_FLOW': '⚪'
  };
  
  const signalIcons = {
    'ACTIVE': '✅',
    'FADE': '⚠️',
    'AVOID': '🚫',
    'CAUTION': '⚠️',
    'MONITOR': '👀',
    'NEUTRAL': '⚪',
    'NO_DATA': '❓'
  };
  
  const colors = {
    'ACTIVE': 'green',
    'DECAY': 'yellow',
    'STRONG_DECAY': 'red',
    'NO_FLOW': 'gray'
  };
  
  const minutesText = decay.lastFlowMinutesAgo !== null 
    ? `${decay.lastFlowMinutesAgo}min ago`
    : 'N/A';
  
  return {
    display: `${statusIcons[decay.status]} ${decay.signal} | Last Flow: ${minutesText}`,
    color: colors[decay.status] || 'gray',
    icon: signalIcons[decay.signal] || '⚪',
    full: decay
  };
}

