/**
 * Generates graded, age-band lesson content for every subject and writes it to
 * data/levels.generated.json (which lib/levels.ts prefers over synthesis).
 *
 * Run with:  npm run seed
 *
 * With a real AI provider (AI_DEMO=false + AI_API_KEY) this produces deep,
 * age-appropriate content. Otherwise it writes fallback levels chunked from the
 * curated base pool, so the file is always valid.
 */
import fs from 'node:fs';
import path from 'node:path';
import { loadEnv } from './load-env';

loadEnv();

import { generateBandLevels } from '../lib/ai/levelgen';
import { SUBJECTS, AGE_BANDS, type AgeBand, type Level } from '../lib/types';
import { canUseAi } from '../lib/env';

const LEVELS_PER_BAND = 30;
const QUESTIONS_PER_LEVEL = 5;

async function main() {
  console.log(`\n🌱 WonderKids content seed (age-band levels)`);
  console.log(`   AI: ${canUseAi() ? 'ON (real generation)' : 'OFF (fallback from base pool)'}`);
  console.log(`   ${LEVELS_PER_BAND} লেভেল × ${QUESTIONS_PER_LEVEL} প্রশ্ন × ৪ band × ৪ বিষয়\n`);

  const out: Record<string, Partial<Record<AgeBand, Level[]>>> = {};

  for (const subject of SUBJECTS) {
    out[subject.id] = {};
    for (const band of AGE_BANDS) {
      process.stdout.write(`   ${subject.name} · ${band.label} … `);
      const levels = await generateBandLevels(
        subject.id,
        band.id,
        LEVELS_PER_BAND,
        QUESTIONS_PER_LEVEL,
      );
      out[subject.id]![band.id] = levels;
      const qCount = levels.reduce((n, l) => n + l.questions.length, 0);
      console.log(`${levels.length} লেভেল, ${qCount} প্রশ্ন`);
    }
  }

  const dir = path.join(process.cwd(), 'data');
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
  const file = path.join(dir, 'levels.generated.json');
  fs.writeFileSync(file, JSON.stringify(out, null, 2), 'utf-8');

  console.log(`\n✅ লেখা হয়েছে: ${path.relative(process.cwd(), file)}\n`);
}

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