/**
 * Mini Backtesting Audit - 5 queries with long delays
 * Tests core backtesting functionality without hitting rate limits
 */

const BASE_URL = 'http://localhost:3000';

const QUERIES = [
  'Backtest betting on NBA home favorites with spreads of -5 or more. What would the expected win rate be?',
  'Test this NFL strategy: Bet on underdogs getting 7+ points in divisional games.',
  'For the 2025-2026 NBA season, test a revenge game strategy.',
  'Backtest a line movement strategy for NBA: Only bet when spread moves 2+ points.',
  'Compare LeBron James vs Kevin Durant this season - who has better stats?',
];

function sleep(ms: number): Promise<void> {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function runQuery(question: string): Promise<any> {
  const startTime = Date.now();

  try {
    const response = await fetch(`${BASE_URL}/api/chat?internal=1`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        messages: [{ role: 'user', content: question }],
        conversationId: `backtest-mini-${Date.now()}`,
      }),
    });

    const latency = (Date.now() - startTime) / 1000;

    if (!response.ok) {
      return { success: false, error: `HTTP ${response.status}`, latency };
    }

    const data = await response.json();
    return { success: true, data, latency };
  } catch (err: any) {
    return { success: false, error: err.message, latency: (Date.now() - startTime) / 1000 };
  }
}

async function runMiniAudit() {
  console.log('Mini Backtesting Audit - 5 Queries');
  console.log('====================================\n');

  let successCount = 0;

  for (let i = 0; i < QUERIES.length; i++) {
    const query = QUERIES[i];
    console.log(`[${i + 1}/5] ${query.substring(0, 60)}...`);

    // Wait 30 seconds between queries to avoid rate limits
    if (i > 0) {
      console.log('   Waiting 30s to avoid rate limits...');
      await sleep(30000);
    }

    const result = await runQuery(query);

    if (result.success) {
      successCount++;
      const ds = result.data.dataSheriff || {};
      const preview = result.data.message?.content?.substring(0, 150) || '';
      console.log(`   ✓ OK (${Math.round((ds.confidence || 0) * 100)}% conf) ${result.latency.toFixed(1)}s`);
      console.log(`   Preview: ${preview.replace(/\n/g, ' ')}...`);
    } else {
      console.log(`   ✗ FAIL: ${result.error}`);
    }
    console.log('');
  }

  console.log('====================================');
  console.log(`Result: ${successCount}/5 successful`);
}

runMiniAudit().catch(console.error);
