import express from 'express';
import { rawQuery } from '../db.js';
import { dailyAnalysisQuery } from '../queries/dailyAnalysisQuery.js';
import { generatePlaybooks, formatPlaybook } from '../services/playbookGenerator.js';
import { backtestStrategy, backtestMultiplePatterns, formatBacktestResults } from '../services/strategyBacktester.js';

const router = express.Router();

router.get('/daily', async (req, res) => {
  try {
    const { lookbackDays = 30, minCrossPercent = 3 } = req.query;
    
    const data = await rawQuery(dailyAnalysisQuery);
    
    // Filter for meaningful moves
    const filtered = data
      .filter(row => Math.abs(row.daily_pct_change) >= minCrossPercent)
      .map(row => ({
        ...row,
        // Classify catalyst strength
        catalystScore: calculateCatalystScore(row),
        // Classify options positioning
        optionsSignal: classifyOptionsSignal(row),
        // Overall trade signal
        tradeSignal: generateTradeSignal(row)
      }))
      .sort((a, b) => new Date(b.trade_date) - new Date(a.trade_date));

    res.json({
      success: true,
      data: filtered,
      count: filtered.length
    });

  } catch (error) {
    console.error('Daily analysis error:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

function calculateCatalystScore(row) {
  let score = 0;
  
  // News factors (1 point each)
  if (row.news_earnings) score += 1;
  if (row.news_fda) score += 1;
  if (row.news_mergers) score += 1;
  if (row.news_rating_up || row.news_rating_dn) score += 0.5;
  
  // Alert factors (0.5 points each)
  if (row.alert_halt) score += 1;
  if (row.alert_price_spike) score += 0.5;
  if (row.alert_52w_high || row.alert_52w_low) score += 0.5;
  
  return score;
}

function classifyOptionsSignal(row) {
  const bullBias = row.opt_notional_bull > row.opt_notional_bear;
  const bearBias = row.opt_notional_bear > row.opt_notional_bull;
  const ratio = bullBias 
    ? row.opt_notional_bull / (row.opt_notional_bear || 1)
    : row.opt_notional_bear / (row.opt_notional_bull || 1);
  
  if (bullBias && ratio >= 2) return 'STRONG_BULL';
  if (bullBias && ratio >= 1.5) return 'BULL';
  if (bearBias && ratio >= 2) return 'STRONG_BEAR';
  if (bearBias && ratio >= 1.5) return 'BEAR';
  return 'NEUTRAL';
}

function generateTradeSignal(row) {
  const priceUp = row.daily_pct_change > 0;
  const optSignal = classifyOptionsSignal(row);
  const hasCatalyst = calculateCatalystScore(row) > 0;
  
  // Bullish signals
  if (priceUp && optSignal.includes('BULL') && hasCatalyst) {
    return { signal: 'BUY', confidence: 'HIGH', reason: 'Catalyst + Options + Price alignment' };
  }
  if (priceUp && optSignal.includes('BULL')) {
    return { signal: 'BUY', confidence: 'MEDIUM', reason: 'Options + Price alignment' };
  }
  
  // Bearish signals
  if (!priceUp && optSignal.includes('BEAR') && hasCatalyst) {
    return { signal: 'SELL', confidence: 'HIGH', reason: 'Catalyst + Options + Price alignment' };
  }
  if (!priceUp && optSignal.includes('BEAR')) {
    return { signal: 'SELL', confidence: 'MEDIUM', reason: 'Options + Price alignment' };
  }
  
  // Divergence signals (counter-trend)
  if (priceUp && optSignal.includes('BEAR')) {
    return { signal: 'FADE', confidence: 'MEDIUM', reason: 'Bearish options despite rally' };
  }
  if (!priceUp && optSignal.includes('BULL')) {
    return { signal: 'REVERSAL', confidence: 'MEDIUM', reason: 'Bullish options despite drop' };
  }
  
  return { signal: 'NEUTRAL', confidence: 'LOW', reason: 'No clear pattern' };
}

/**
 * GET /api/analysis/playbooks
 * Get auto-generated playbooks from historical patterns
 */
router.get('/playbooks', async (req, res) => {
  try {
    const { lookbackDays = 90, minOccurrences = 5, minWinRate = 0.60 } = req.query;
    
    const playbooks = await generatePlaybooks({
      lookbackDays: parseInt(lookbackDays),
      minOccurrences: parseInt(minOccurrences),
      minWinRate: parseFloat(minWinRate)
    });
    
    const formatted = playbooks.map(p => formatPlaybook(p));
    
    res.json({
      success: true,
      playbooks: formatted,
      raw: playbooks,
      count: playbooks.length
    });
  } catch (error) {
    console.error('Playbook generation error:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

/**
 * POST /api/analysis/backtest
 * Backtest a strategy/pattern
 */
router.post('/backtest', async (req, res) => {
  try {
    const { pattern, options } = req.body;
    
    if (!pattern) {
      return res.status(400).json({
        success: false,
        error: 'Pattern definition is required'
      });
    }
    
    const results = await backtestStrategy(pattern, options);
    const formatted = formatBacktestResults(results);
    
    res.json({
      success: true,
      results: formatted,
      raw: results
    });
  } catch (error) {
    console.error('Backtest error:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

/**
 * POST /api/analysis/backtest-multiple
 * Backtest multiple patterns
 */
router.post('/backtest-multiple', async (req, res) => {
  try {
    const { patterns, options } = req.body;
    
    if (!patterns || !Array.isArray(patterns)) {
      return res.status(400).json({
        success: false,
        error: 'Patterns array is required'
      });
    }
    
    const results = await backtestMultiplePatterns(patterns, options);
    const formatted = results.map(r => formatBacktestResults(r));
    
    res.json({
      success: true,
      results: formatted,
      raw: results,
      topStrategies: formatted.slice(0, 10) // Top 10
    });
  } catch (error) {
    console.error('Backtest multiple error:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

export default router;
