/**
 * Run Targeted Historical Feeder Script
 * Fetches matches only for leagues in top_leagues.json for the last ~2.5 seasons.
 */

process.env.FEEDER_MODE = "historical";

import { NestFactory } from "@nestjs/core";
import { AppModule } from "../app.module";
import { FeederService } from "../modules/feeder/feeder.service";
import { Logger } from "@nestjs/common";
import * as fs from "fs";
import * as path from "path";

async function bootstrap() {
  const logger = new Logger("FeederFilteredScript");
  logger.log("🚀 Starting Targeted Historical Feeder...");

  // Read top_leagues.json
  const leaguesPath = path.join(process.cwd(), "top_leagues.json");
  let targetLeagues: string[] = [];
  try {
    const data = fs.readFileSync(leaguesPath, "utf8");
    targetLeagues = JSON.parse(data);
    // Deduplicate
    targetLeagues = [...new Set(targetLeagues)];
    logger.log(
      `✅ Loaded ${targetLeagues.length} unique target leagues from top_leagues.json`,
    );
  } catch (e: unknown) {
    const message = e instanceof Error ? e.message : String(e);
    logger.error(`❌ Failed to load top_leagues.json: ${message}`);
    process.exit(1);
  }

  const app = await NestFactory.createApplicationContext(AppModule, {
    logger: ["log", "error", "warn"],
  });

  try {
    const feederService = app.get(FeederService);
    // Start from 2023-07-01 to cover 2023-2024, 2024-2025, and current 2025-2026 seasons
    const START_DATE = "2023-07-01";
    logger.log(`📅 Date Range: ${START_DATE} -> Today`);

    await feederService.runHistoricalScan(
      ["football"],
      START_DATE,
      targetLeagues,
    );
    logger.log("✅ Targeted Feeder completed successfully!");
  } catch (error: any) {
    logger.error(`❌ Feeder failed: ${error.message}`);
    logger.error(error.stack);
    process.exit(1);
  } finally {
    await app.close();
  }

  process.exit(0);
}

void bootstrap();
