import { buildSportsWeatherMapPrompt } from '../src/services/sports-weather-map-prompt';
import type { PublicTopPicksResponseV1 } from '../src/contracts/forecast-public-contract';

type Args = {
  league: string;
  limit: number;
  clipSeconds: number;
  clipCount: number;
  aspectRatio: string;
  baseUrl: string;
  json: boolean;
};

function parseArgs(argv: string[]): Args {
  const args: Args = {
    league: 'nba',
    limit: 3,
    clipSeconds: 8,
    clipCount: 4,
    aspectRatio: '9:16',
    baseUrl: process.env.RAINMAKER_API_BASE || 'https://rainmakersports.app/api',
    json: false,
  };

  for (let index = 0; index < argv.length; index += 1) {
    const token = argv[index];
    const next = argv[index + 1];
    if (token === '--league' && next) {
      args.league = next;
      index += 1;
    } else if (token === '--limit' && next) {
      args.limit = Math.max(1, Math.min(12, Number(next) || 3));
      index += 1;
    } else if (token === '--clip-seconds' && next) {
      args.clipSeconds = Number(next) || 8;
      index += 1;
    } else if (token === '--clip-count' && next) {
      args.clipCount = Number(next) || 4;
      index += 1;
    } else if (token === '--aspect-ratio' && next) {
      args.aspectRatio = next;
      index += 1;
    } else if (token === '--base-url' && next) {
      args.baseUrl = next.replace(/\/+$/, '');
      index += 1;
    } else if (token === '--json') {
      args.json = true;
    }
  }

  return args;
}

async function fetchTopPicks(args: Args): Promise<PublicTopPicksResponseV1> {
  const url = new URL(`${args.baseUrl}/forecast/top-picks`);
  url.searchParams.set('league', args.league);
  url.searchParams.set('limit', String(Math.max(args.limit * 3, 8)));

  const response = await fetch(url.toString(), {
    headers: {
      Accept: 'application/json',
      'User-Agent': 'rainmaker-sports-weather-map-prompt/1.0',
    },
  });

  if (!response.ok) {
    throw new Error(`Failed to fetch top picks (${response.status} ${response.statusText})`);
  }

  return await response.json() as PublicTopPicksResponseV1;
}

async function main(): Promise<void> {
  const args = parseArgs(process.argv.slice(2));
  const topPicks = await fetchTopPicks(args);
  const result = buildSportsWeatherMapPrompt(topPicks, {
    clipSeconds: args.clipSeconds,
    clipCount: args.clipCount,
    aspectRatio: args.aspectRatio,
  });

  if (args.json) {
    console.log(JSON.stringify(result, null, 2));
    return;
  }

  console.log(result.prompt);
}

main().catch((error) => {
  console.error(error instanceof Error ? error.message : String(error));
  process.exit(1);
});
