#!/usr/bin/env npx ts-node
/**
 * Seed NCAAB CanonicalTeam entries from PlayerGameModel data.
 *
 * NCAAB has 0 CanonicalTeam entries despite 350+ teams in PGM.
 * This script auto-seeds from existing PGM distinct team names.
 *
 * Usage:
 *   npx ts-node src/scripts/seed-ncaab-teams.ts
 *   npx ts-node src/scripts/seed-ncaab-teams.ts --dry-run
 */

import { Pool } from 'pg';
import dotenv from 'dotenv';
import path from 'path';
import { buildDatabasePoolConfig } from '../db/config';

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

const pool = new Pool(buildDatabasePoolConfig({
  max: 5,
  idleTimeoutMillis: 10_000,
}));

const DRY_RUN = process.argv.includes('--dry-run');

async function main() {
  console.log('='.repeat(80));
  console.log('NCAAB CanonicalTeam Seeder');
  console.log(`Mode: ${DRY_RUN ? 'DRY RUN' : 'LIVE'}`);
  console.log('='.repeat(80));

  // Get distinct NCAAB team names from PlayerGameModel
  const { rows: pgmTeams } = await pool.query(
    `SELECT DISTINCT "teamName" FROM "PlayerGameModel" WHERE league = 'ncaab' AND "teamName" IS NOT NULL ORDER BY "teamName"`
  );
  console.log(`\nFound ${pgmTeams.length} distinct NCAAB teams in PlayerGameModel`);

  // Get existing CanonicalTeam entries for ncaab
  const { rows: existingTeams } = await pool.query(
    `SELECT name FROM "CanonicalTeam" WHERE league = 'ncaab'`
  );
  const existingNames = new Set(existingTeams.map((r: any) => r.name.toLowerCase()));
  console.log(`Existing CanonicalTeam entries for ncaab: ${existingTeams.length}`);

  let created = 0;
  let skipped = 0;

  for (const row of pgmTeams) {
    const teamName: string = row.teamName.trim();
    if (!teamName) continue;

    if (existingNames.has(teamName.toLowerCase())) {
      skipped++;
      continue;
    }

    if (DRY_RUN) {
      console.log(`  [DRY] Would create: ${teamName}`);
      created++;
      continue;
    }

    try {
      // Create CanonicalTeam
      const { rows: inserted } = await pool.query(
        `INSERT INTO "CanonicalTeam" (name, league, "createdAt", "updatedAt")
         VALUES ($1, 'ncaab', NOW(), NOW())
         ON CONFLICT DO NOTHING
         RETURNING id`,
        [teamName]
      );

      if (inserted.length > 0) {
        // Create TeamAlias linking the PGM name
        await pool.query(
          `INSERT INTO "TeamAlias" ("canonicalTeamId", alias, source, "createdAt", "updatedAt")
           VALUES ($1, $2, 'pgm_seed', NOW(), NOW())
           ON CONFLICT DO NOTHING`,
          [inserted[0].id, teamName]
        );
        created++;
      } else {
        skipped++;
      }
    } catch (err: any) {
      console.error(`  [ERR] ${teamName}: ${err.message}`);
    }
  }

  console.log(`\nDone: ${created} created, ${skipped} skipped`);
  await pool.end();
}

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