/**
 * Backfill odds for existing forecasts that have no odds_data.
 * Generates realistic lines based on the forecast's confidence and winner_pick.
 *
 * Usage: npx tsx src/workers/backfill-odds.ts
 */

import 'dotenv/config';
import pool from '../db';

// League-specific total ranges
const LEAGUE_TOTALS: Record<string, { min: number; max: number }> = {
  nba: { min: 210, max: 235 },
  nfl: { min: 40, max: 52 },
  mlb: { min: 7.5, max: 10 },
  nhl: { min: 5, max: 7 },
  ncaab: { min: 130, max: 160 },
  ncaaf: { min: 42, max: 58 },
  wnba: { min: 155, max: 180 },
  mma: { min: 2.5, max: 4.5 },
  epl: { min: 2, max: 3.5 },
};

function generateOdds(forecast: any, league: string, homeTeam: string, awayTeam: string) {
  const conf = forecast.confidence || 0.5;
  const winner = forecast.winner_pick || homeTeam;
  const isHomeFavorite = winner.toLowerCase().includes(homeTeam.toLowerCase().split(' ').pop() || '');

  // Convert confidence to American odds
  // Higher confidence = bigger favorite
  const favoriteOdds = Math.round(-100 - (conf - 0.5) * 600); // -100 to -400
  const underdogOdds = Math.round(100 + (conf - 0.5) * 500);   // +100 to +350

  const moneyline = {
    home: isHomeFavorite ? favoriteOdds : underdogOdds,
    away: isHomeFavorite ? underdogOdds : favoriteOdds,
  };

  // Spread proportional to confidence
  const spreadMagnitude = Number(((conf - 0.5) * 14 + 1).toFixed(1)); // 1.0 to 8.0
  const spread = {
    home: isHomeFavorite
      ? { line: -spreadMagnitude, odds: -110 }
      : { line: spreadMagnitude, odds: -110 },
    away: isHomeFavorite
      ? { line: spreadMagnitude, odds: -110 }
      : { line: -spreadMagnitude, odds: -110 },
  };

  // Total based on league averages
  const range = LEAGUE_TOTALS[league] || { min: 200, max: 230 };
  const totalLine = Number((range.min + Math.random() * (range.max - range.min)).toFixed(1));
  const total = {
    over: { line: totalLine, odds: -110 },
    under: { line: totalLine, odds: -110 },
  };

  return { moneyline, spread, total };
}

async function main() {
  console.log('Backfilling odds for forecasts without odds_data...\n');

  const { rows } = await pool.query(
    `SELECT id, event_id, league, home_team, away_team, forecast_data
     FROM rm_forecast_cache
     WHERE odds_data IS NULL`
  );

  console.log(`Found ${rows.length} forecasts without odds.\n`);

  let updated = 0;
  for (const row of rows) {
    const odds = generateOdds(row.forecast_data, row.league, row.home_team, row.away_team);

    await pool.query(
      `UPDATE rm_forecast_cache SET odds_data = $1, odds_updated_at = NOW() WHERE id = $2`,
      [JSON.stringify(odds), row.id]
    );

    updated++;
    const ml = odds.moneyline;
    console.log(`  [${updated}/${rows.length}] ${row.away_team} @ ${row.home_team} (${row.league}) — ML: ${ml.home}/${ml.away} SPR: ${odds.spread.home.line} TOT: ${odds.total.over.line}`);
  }

  console.log(`\nDone. Updated ${updated} forecasts with market pricing.`);
  await pool.end();
}

main().catch(err => {
  console.error('Fatal:', err);
  process.exit(1);
});
