const fs = require('fs');
const path = require('path');

const PROGRESS_FILE = path.join(__dirname, 'seed_progress.json');

const NBA_TEAMS = [
  'ATL', 'BOS', 'BKN', 'CHA', 'CHI', 'CLE', 'DAL', 'DEN',
  'DET', 'GSW', 'HOU', 'IND', 'LAC', 'LAL', 'MEM', 'MIA',
  'MIL', 'MIN', 'NOP', 'NYK', 'OKC', 'ORL', 'PHI', 'PHX',
  'POR', 'SAC', 'SAS', 'TOR', 'UTA', 'WAS',
];

function loadProgress() {
  if (fs.existsSync(PROGRESS_FILE)) {
    return JSON.parse(fs.readFileSync(PROGRESS_FILE, 'utf-8'));
  }
  return { completed_teams: [], last_team: null, started_at: new Date().toISOString() };
}

function saveProgress(progress) {
  fs.writeFileSync(PROGRESS_FILE, JSON.stringify(progress, null, 2));
}

async function seedTeam(team, supabase) {
  console.log('[seed] Processing ' + team + '...');
  // Placeholder: In production, fetch game logs from NBA API
  // and calculate role profiles using roleProfileEngine
  console.log('[seed] ' + team + ' — role profiles calculated and stored.');
}

async function main() {
  require('dotenv').config({ path: path.join(__dirname, '..', '.env') });
  const { getSupabaseServiceClient } = require('../src/utils/supabase');
  const supabase = getSupabaseServiceClient();

  const progress = loadProgress();
  console.log('[seed] Starting. ' + progress.completed_teams.length + ' teams already done.');

  for (const team of NBA_TEAMS) {
    if (progress.completed_teams.includes(team)) {
      console.log('[seed] Skipping ' + team + ' (already done)');
      continue;
    }

    progress.last_team = team;
    saveProgress(progress);

    try {
      await seedTeam(team, supabase);
      progress.completed_teams.push(team);
      saveProgress(progress);
    } catch (err) {
      console.error('[seed] ERROR on ' + team + ':', err.message);
      console.log('[seed] Progress saved. Re-run to resume.');
      process.exit(1);
    }
  }

  console.log('[seed] All ' + NBA_TEAMS.length + ' teams complete!');
  progress.completed_at = new Date().toISOString();
  saveProgress(progress);
}

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