import 'dotenv/config';

import pool from '../db';
import { buildForecastFromCuratedEvent } from '../services/forecast-builder';

const args = process.argv.slice(2);
const dryRun = args.includes('--dry-run');

function getArg(flag: string): string | null {
  const idx = args.indexOf(flag);
  return idx >= 0 && idx + 1 < args.length ? args[idx + 1] : null;
}

function getTodayET(): string {
  return new Date().toLocaleDateString('en-CA', { timeZone: 'America/New_York' });
}

async function main() {
  const league = getArg('--league');
  const eventId = getArg('--event');
  const limitArg = getArg('--limit');
  const limit = limitArg ? Math.max(1, parseInt(limitArg, 10) || 0) : null;
  const todayET = getTodayET();

  const where: string[] = [
    `DATE(e.starts_at AT TIME ZONE 'America/New_York') = $1`,
  ];
  const params: any[] = [todayET];

  if (league) {
    params.push(league);
    where.push(`e.league = $${params.length}`);
  }
  if (eventId) {
    params.push(eventId);
    where.push(`e.event_id = $${params.length}`);
  }

  let sql = `
    SELECT e.event_id, e.league, e.home_team, e.away_team, e.home_short, e.away_short,
           e.starts_at, e.moneyline, e.spread, e.total
    FROM rm_events e
    WHERE ${where.join(' AND ')}
    ORDER BY e.starts_at ASC
  `;

  if (limit != null) {
    params.push(limit);
    sql += ` LIMIT $${params.length}`;
  }

  const { rows } = await pool.query(sql, params);
  console.log(`[refresh-today] ${todayET} | found ${rows.length} curated event(s)`);

  if (rows.length === 0) {
    await pool.end();
    return;
  }

  let refreshed = 0;
  let failed = 0;

  for (const row of rows) {
    const label = `${row.away_team} @ ${row.home_team} (${String(row.league).toUpperCase()})`;

    if (dryRun) {
      console.log(`[refresh-today] [DRY RUN] ${label}`);
      continue;
    }

    try {
      const result = await buildForecastFromCuratedEvent(row);
      refreshed += 1;
      console.log(`[refresh-today] [OK] ${label} -> ${result.forecastId}`);
    } catch (err: any) {
      failed += 1;
      console.error(`[refresh-today] [FAIL] ${label}: ${err.message}`);
    }
  }

  console.log(`[refresh-today] complete | refreshed=${refreshed} failed=${failed}`);
  await pool.end();
  process.exit(failed > 0 ? 1 : 0);
}

main().catch(async (err) => {
  console.error('[refresh-today] fatal:', err);
  await pool.end();
  process.exit(1);
});
