import dotenv from 'dotenv';
import path from 'path';
dotenv.config({ path: path.join(__dirname, '../../.env') });

import pool from '../db';
import { upsertAccuracyV2FromRow } from '../services/grading-service';

async function main() {
  console.log(`[${new Date().toISOString()}] Starting rm_forecast_accuracy_v2 backfill...`);

  const { rows } = await pool.query(
    `SELECT forecast_id, event_id, league, predicted_winner, actual_winner,
            predicted_spread, actual_spread, predicted_total, actual_total,
            accuracy_bucket, accuracy_pct, resolved_at, event_date, home_score, away_score,
            original_forecast, benchmark_forecast, closing_market, final_grade, grading_policy,
            forecast_type, benchmark_source
     FROM rm_forecast_accuracy
     ORDER BY resolved_at ASC NULLS FIRST, event_date ASC NULLS FIRST, id ASC`
  );

  let synced = 0;
  for (const row of rows) {
    await upsertAccuracyV2FromRow(row);
    synced++;
    if (synced % 250 === 0) {
      console.log(`  synced ${synced}/${rows.length}`);
    }
  }

  console.log(`Backfill complete. Synced ${synced} rows.`);
  await pool.end();
}

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