import { rawQuery } from '../db.js';
import { calculateBadges } from './badgeCalculator.js';

/**
 * Detects flow reversals (badge color flips)
 * Compares current badges vs 15min ago vs 30min ago
 */

export async function detectReversals(symbolList) {
  const reversals = [];

  for (const symbol of symbolList) {
    const flowHistory = await getFlowHistory(symbol, 30); // last 30min

    if (flowHistory.length < 2) continue;

    // Calculate badges for each flow entry
    const flowHistoryWithBadges = flowHistory.map(flow => {
      const badges = calculateBadges(flow);
      const timestamp = flow.flow_ts_utc ? new Date(flow.flow_ts_utc) : 
                        flow.CreatedDate ? new Date(flow.CreatedDate) : 
                        new Date();
      return {
        ...flow,
        badges,
        timestamp: timestamp.getTime(),
        timestampDate: timestamp
      };
    });

    // Sort by timestamp descending (most recent first)
    flowHistoryWithBadges.sort((a, b) => b.timestamp - a.timestamp);

    if (flowHistoryWithBadges.length < 2) continue;

    const current = flowHistoryWithBadges[0];
    const currentTime = current.timestamp;
    
    // Find flow from approximately 15 minutes ago (within 10-20 minute window)
    const prev15min = flowHistoryWithBadges.find(f => {
      const timeDiff = (currentTime - f.timestamp) / (1000 * 60); // minutes
      return timeDiff >= 10 && timeDiff <= 20; // Between 10-20 min before current
    });

    if (!prev15min) continue;

    // Check if badge color flipped
    const currentBadge = current.badges?.round;
    const prevBadge = prev15min.badges?.round;

    if (currentBadge !== prevBadge && currentBadge && prevBadge) {
      const currentSpot = parseFloat(current.spot_num || current.u_close || 0);
      const prevSpot = parseFloat(prev15min.spot_num || prev15min.u_close || 0);
      const priceChange = prevSpot > 0 
        ? (((currentSpot - prevSpot) / prevSpot) * 100).toFixed(2) + '%'
        : '0%';

      const reversal = {
        symbol: symbol.toUpperCase(),
        from: prevBadge,
        to: currentBadge,
        timestamp: new Date(current.timestamp).toISOString(),
        currentPremium: parseFloat(current.premium_num || 0),
        previousPremium: parseFloat(prev15min.premium_num || 0),
        priceChange,
        signal: currentBadge === '🟢' ? 'REVERSAL_BULLISH' : 'REVERSAL_BEARISH'
      };

      reversals.push(reversal);
    }
  }

  return reversals;
}

async function getFlowHistory(symbol, minutes) {
  try {
    // Query database for flow history using OptionsFlow_monthly
    const query = `
      SELECT 
        UPPER(TRIM("Symbol")) as symbol_norm,
        ("CreatedDate" || ' ' || COALESCE("CreatedTime", '00:00:00'))::timestamp as flow_ts_utc,
        NULLIF(REGEXP_REPLACE("Premium"::text, '[\\s$,]', '', 'g'),'')::numeric as premium_num,
        NULLIF(REGEXP_REPLACE("Spot"::text, '[\\s$,]', '', 'g'),'')::numeric as spot_num,
        NULLIF(REGEXP_REPLACE("Price"::text, '[\\s$,]', '', 'g'),'')::numeric as u_close,
        NULL::numeric as bull_prem_itm,
        NULL::numeric as bear_prem_itm,
        NULL::numeric as prem_cb_itm,
        NULL::numeric as prem_ps_itm,
        NULL::numeric as prem_pb_itm,
        NULL::numeric as prem_cs_itm,
        NULL::numeric as prem_cb_otm,
        NULL::numeric as prem_ps_otm,
        NULL::numeric as prem_pb_otm,
        NULL::numeric as prem_cs_otm,
        NULL::numeric as oi_cb_otm,
        NULL::numeric as oi_pb_otm,
        NULLIF(REGEXP_REPLACE("Volume"::text, '[\\s$,]', '', 'g'),'')::numeric as vol_num,
        NULLIF(REGEXP_REPLACE("OI"::text, '[\\s$,]', '', 'g'),'')::numeric as oi_num,
        CASE WHEN UPPER(TRIM("CallPut")) IN ('C','CALL','CALLS','CE') THEN 'CALL'
             WHEN UPPER(TRIM("CallPut")) IN ('P','PUT','PUTS','PE') THEN 'PUT'
        END as cp_norm,
        CASE
          WHEN UPPER(TRIM("Side")) IN ('A','AA','ASK','BUY','BOT','BTO','AT_ASK') THEN 'BUY'
          WHEN UPPER(TRIM("Side")) IN ('B','BB','BID','SELL','SLD','STO','AT_BID') THEN 'SELL'
        END as side_norm,
        "CreatedDate"
      FROM public."OptionsFlow_monthly"
      WHERE UPPER(TRIM("Symbol")) = $1
        AND ("CreatedDate" || ' ' || COALESCE("CreatedTime", '00:00:00'))::timestamp >= NOW() - INTERVAL '${minutes} minutes'
      ORDER BY ("CreatedDate" || ' ' || COALESCE("CreatedTime", '00:00:00'))::timestamp DESC
      LIMIT 100
    `;
    return await rawQuery(query, [symbol.toUpperCase()]);
  } catch (error) {
    console.error(`Error getting flow history for ${symbol}:`, error);
    return [];
  }
}