/**
 * Test Script: Probe SportsGameOdds API Historical Data Limits
 *
 * This script tests how far back the SGO API provides data by querying
 * various historical date ranges and reporting what comes back.
 *
 * Usage: npx tsx src/scripts/testSgoHistoricalData.ts
 */

import * as dotenv from 'dotenv';
dotenv.config({ path: '.env.local' });
dotenv.config({ path: '.env' });

import SportsGameOdds from 'sports-odds-api';

const API_KEY = process.env.SPORTSGAMEODDS_API_KEY || '';

if (!API_KEY) {
  console.error('❌ SPORTSGAMEODDS_API_KEY not set');
  process.exit(1);
}

const client = new SportsGameOdds({
  apiKeyHeader: API_KEY,
  maxRetries: 2,
  timeout: 30000,
});

interface TestResult {
  dateRange: string;
  eventsFound: number;
  eventsWithOdds: number;
  eventsWithProps: number;
  sampleTeams: string[];
  propTypes: Set<string>;
}

async function testDateRange(
  league: string,
  leagueID: string,
  startDate: string,
  endDate: string
): Promise<TestResult> {
  const result: TestResult = {
    dateRange: `${startDate} to ${endDate}`,
    eventsFound: 0,
    eventsWithOdds: 0,
    eventsWithProps: 0,
    sampleTeams: [],
    propTypes: new Set(),
  };

  try {
    const events: any[] = [];

    // SDK uses startsAfter/startsBefore, not startDate/endDate
    for await (const event of client.events.get({
      leagueID,
      startsAfter: startDate,
      startsBefore: endDate,
      limit: 50,
    })) {
      events.push(event);
      if (events.length >= 50) break;
    }

    result.eventsFound = events.length;

    for (const event of events) {
      const odds = event?.odds || {};
      const oddsKeys = Object.keys(odds);

      if (oddsKeys.length > 0) {
        result.eventsWithOdds++;

        // Check for player props
        let hasProps = false;
        for (const key of oddsKeys) {
          // Player prop patterns include player IDs like LEBRON_JAMES_1_NBA
          if (key.match(/[A-Z]+_[A-Z]+_\d+_[A-Z]+/)) {
            hasProps = true;
            const propType = key.split('-')[0];
            result.propTypes.add(propType);
          }
        }

        if (hasProps) {
          result.eventsWithProps++;
        }
      }

      // Collect sample teams
      if (result.sampleTeams.length < 3) {
        const home = event?.teams?.home?.names?.short || '';
        const away = event?.teams?.away?.names?.short || '';
        if (home && away) {
          result.sampleTeams.push(`${away} @ ${home}`);
        }
      }
    }
  } catch (error: any) {
    console.error(`  ⚠️ Error for ${startDate}: ${error?.message || error}`);
  }

  return result;
}

async function runTests() {
  console.log('🔍 Testing SportsGameOdds Historical Data Availability\n');
  console.log('=' .repeat(70));

  const leagues = [
    { name: 'NBA', id: 'NBA' },
    { name: 'NFL', id: 'NFL' },
    { name: 'NHL', id: 'NHL' },
    { name: 'MLB', id: 'MLB' },
  ];

  // Test date ranges - from recent to historical
  const today = new Date();
  const testDates = [
    // Recent (should have data)
    { label: 'Today', start: formatDate(today), end: formatDate(today) },
    { label: 'Last 7 days', start: formatDate(daysAgo(7)), end: formatDate(today) },
    { label: 'Last 30 days', start: formatDate(daysAgo(30)), end: formatDate(daysAgo(23)) },

    // Recent past (might have data)
    { label: 'Dec 2025', start: '2025-12-01', end: '2025-12-07' },
    { label: 'Nov 2025', start: '2025-11-01', end: '2025-11-07' },
    { label: 'Oct 2025', start: '2025-10-01', end: '2025-10-07' },
    { label: 'Jun 2025', start: '2025-06-01', end: '2025-06-07' },

    // Historical (likely no data)
    { label: 'Jan 2025', start: '2025-01-01', end: '2025-01-07' },
    { label: 'Dec 2024', start: '2024-12-01', end: '2024-12-07' },
    { label: 'Jun 2024', start: '2024-06-01', end: '2024-06-07' },
    { label: 'Jan 2024', start: '2024-01-01', end: '2024-01-07' },
    { label: 'Jan 2023', start: '2023-01-01', end: '2023-01-07' },
  ];

  const allResults: Map<string, TestResult[]> = new Map();

  for (const league of leagues) {
    console.log(`\n📊 Testing ${league.name}...\n`);
    const leagueResults: TestResult[] = [];

    for (const dateRange of testDates) {
      process.stdout.write(`  ${dateRange.label.padEnd(15)} `);

      const result = await testDateRange(
        league.name.toLowerCase(),
        league.id,
        dateRange.start,
        dateRange.end
      );

      leagueResults.push(result);

      // Format output
      if (result.eventsFound === 0) {
        console.log('❌ No events');
      } else if (result.eventsWithProps > 0) {
        console.log(
          `✅ ${result.eventsFound} events, ${result.eventsWithOdds} with odds, ` +
          `${result.eventsWithProps} with props (${[...result.propTypes].slice(0, 3).join(', ')})`
        );
      } else if (result.eventsWithOdds > 0) {
        console.log(`⚠️  ${result.eventsFound} events, ${result.eventsWithOdds} with odds, NO props`);
      } else {
        console.log(`⚠️  ${result.eventsFound} events, NO odds data`);
      }

      // Rate limit - small delay between requests
      await sleep(500);
    }

    allResults.set(league.name, leagueResults);
  }

  // Summary
  console.log('\n' + '='.repeat(70));
  console.log('📋 SUMMARY: Historical Data Availability\n');

  for (const [league, results] of allResults) {
    const withProps = results.filter(r => r.eventsWithProps > 0);
    const withOdds = results.filter(r => r.eventsWithOdds > 0);
    const withEvents = results.filter(r => r.eventsFound > 0);

    if (withProps.length > 0) {
      const oldestWithProps = withProps[withProps.length - 1];
      console.log(`${league}: Props available back to ${oldestWithProps.dateRange.split(' ')[0]}`);
    } else if (withOdds.length > 0) {
      const oldestWithOdds = withOdds[withOdds.length - 1];
      console.log(`${league}: Odds (no props) available back to ${oldestWithOdds.dateRange.split(' ')[0]}`);
    } else if (withEvents.length > 0) {
      console.log(`${league}: Events (no odds) only`);
    } else {
      console.log(`${league}: No historical data found`);
    }
  }

  console.log('\n' + '='.repeat(70));
  console.log('💡 Conclusion:');
  console.log('   - If props are only available for recent dates, SGO doesn\'t archive historical props');
  console.log('   - We would need an alternative data source for pre-2026 prop data');
  console.log('   - Consider: sportsbookreview archives, actionnetwork, or paid data providers\n');
}

// Helpers
function formatDate(d: Date): string {
  return d.toISOString().slice(0, 10);
}

function daysAgo(n: number): Date {
  const d = new Date();
  d.setDate(d.getDate() - n);
  return d;
}

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

// Run
runTests().catch(console.error);
