/**
 * Test Data Sheriff processing of backtesting queries
 * Tests entity resolution and context building WITHOUT calling Grok API
 */

import { dataSheriffAgent } from '../src/agents/dataSheriff';

const BACKTEST_QUERIES = [
  // Team-based strategies
  'Backtest betting on NBA home favorites with spreads of -5 or more',
  'Test this NFL strategy: Bet on underdogs getting 7+ points in divisional games',
  'How would betting the OVER on NBA games with totals above 235 perform?',
  'Show me projected performance of betting against MLB teams on 3+ game losing streaks',
  'Backtest NHL home underdogs for the 2025-2026 season',

  // Player-based strategies
  'Test betting OVER on LeBron James points when Lakers are favorites',
  'Backtest Patrick Mahomes passing yards OVER in home games',
  'Project Stephen Curry three-point props performance',

  // Matchup strategies
  'Lakers vs Celtics - backtest the home team spread',
  'Chiefs vs Raiders - test betting the underdog historically',
  'Bills vs Ravens spread analysis using historical data',

  // Complex strategies
  'Compare LeBron James vs Kevin Durant stats for prop betting',
  'Test a revenge game strategy for NBA teams',
  'Backtest line movement strategy - bet when spread moves 2+ points',
];

async function testDataSheriff() {
  console.log('Data Sheriff Backtesting Query Analysis');
  console.log('========================================\n');
  console.log('Testing entity resolution and context building for strategy queries.\n');

  let successCount = 0;
  let totalConfidence = 0;
  let totalCoverage = 0;
  const entityStats = {
    teamsFound: 0,
    playersFound: 0,
    gamesContext: 0,
  };

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

    try {
      const result = await dataSheriffAgent.processQuery(query);

      const conf = Math.round((result.metadata?.confidenceScore || 0) * 100);
      const cov = Math.round((result.metadata?.coverageScore || 0) * 100);

      totalConfidence += result.metadata?.confidenceScore || 0;
      totalCoverage += result.metadata?.coverageScore || 0;
      successCount++;

      // Count entities from deconstructedQuery
      const entities = result.deconstructedQuery?.entities || [];
      const teams = entities.filter((e: any) => e.type === 'team');
      const players = entities.filter((e: any) => e.type === 'player');
      entityStats.teamsFound += teams.length;
      entityStats.playersFound += players.length;

      // Count games in context
      const contextForLLM = result.contextForLLM || '';
      const gamesMatch = contextForLLM.match(/Game \d+:|recent games|game data/gi);
      const gamesCount = gamesMatch ? gamesMatch.length : 0;
      entityStats.gamesContext += gamesCount > 0 ? 1 : 0;

      console.log(`   ✓ Conf: ${conf}% | Cov: ${cov}%`);
      console.log(`   Entities: ${teams.length} teams, ${players.length} players`);

      // Show resolved entities
      if (teams.length > 0) {
        console.log(`   Teams: ${teams.map((t: any) => t.resolvedId || t.name).join(', ')}`);
      }
      if (players.length > 0) {
        console.log(`   Players: ${players.map((p: any) => p.resolvedId || p.name).join(', ')}`);
      }

      // Show corrections from validation
      const corrections = result.validation?.corrections || [];
      if (corrections.length > 0) {
        console.log(`   Corrections: ${corrections.map((c: any) => `${c.original}→${c.corrected}`).join(', ')}`);
      }

      // Show warnings
      const warnings = result.validation?.warnings || [];
      if (warnings.length > 0) {
        console.log(`   ⚠ Warnings: ${warnings.join(', ')}`);
      }

      // Show intent
      const intent = result.deconstructedQuery?.intent?.primary || 'unknown';
      console.log(`   Intent: ${intent}`);

    } catch (err: any) {
      console.log(`   ✗ Error: ${err.message}`);
    }
    console.log('');
  }

  // Summary
  console.log('========================================');
  console.log('SUMMARY');
  console.log('========================================');
  console.log(`Successful:     ${successCount}/${BACKTEST_QUERIES.length}`);
  console.log(`Avg Confidence: ${Math.round(totalConfidence / successCount * 100)}%`);
  console.log(`Avg Coverage:   ${Math.round(totalCoverage / successCount * 100)}%`);
  console.log('');
  console.log('Entity Resolution:');
  console.log(`  Teams found:   ${entityStats.teamsFound}`);
  console.log(`  Players found: ${entityStats.playersFound}`);
  console.log(`  With game context: ${entityStats.gamesContext}`);
  console.log('');

  if (successCount === BACKTEST_QUERIES.length) {
    console.log('✓ Data Sheriff successfully processed all backtesting queries');
    console.log('  Entity resolution and context building working correctly.');
    console.log('');
    console.log('Note: Grok API is currently rate-limited from the previous audit.');
    console.log('Run the full backtest-audit.ts later when limits reset.');
  } else {
    console.log('⚠ Some queries failed - check entity resolution logic');
  }
}

testDataSheriff().catch(console.error);
