/**
 * Raseedna — content migration seed.
 *
 * Loads the REAL content extracted from the legacy WordPress theme
 * (raseedna-theme-fixed.zip) into the new independent database. The JSON
 * files under prisma/data/ were generated by directly invoking the theme's
 * own pure data functions (raseedna_all_chapters_data(),
 * raseedna_demo_dictionary_data(), raseedna_seed_demo_parent_guide()) via
 * PHP CLI, NOT retyped or reinvented — see docs/CONTENT-MIGRATION.md.
 *
 * Safe to re-run: wipes and rebuilds seed-derived tables only (never touches
 * users, progress, points, or activation codes).
 */
import { PrismaClient } from '@prisma/client';
import * as fs from 'fs';
import * as path from 'path';

const prisma = new PrismaClient();

const LEVEL_META: Record<string, { title: string; description: string }> = {
  '1': { title: 'رحلة المال', description: 'أساسيات المال — 14 فصلاً من كتاب "ما لا يتعلمونه في المدرسة".' },
  '2': { title: 'بناء الثروة', description: 'محتوى أصيل تكميلي (غير مقتبس من الكتاب) عن بناء القيمة والثروة.' },
  '3': { title: 'ريادة المستقبل', description: 'محتوى أصيل تكميلي (غير مقتبس من الكتاب) عن ريادة الأعمال المتقدمة.' },
};

function loadJson<T>(rel: string): T {
  return JSON.parse(fs.readFileSync(path.join(__dirname, 'data', rel), 'utf-8'));
}

interface SeedQuestion {
  text: string;
  options: string[];
  correct: number; // 1-3
  explanation: string;
}
interface SeedChapter {
  title: string;
  icon: string;
  short_description: string;
  teaser: string;
  questions: SeedQuestion[];
}
type SeedChaptersByLevel = Record<string, SeedChapter[]>;

interface SeedTerm {
  term: string;
  explanation: string;
  category: string;
  icon: string;
}

interface SeedGuideTip {
  title: string;
  content: string;
  menu_order: number;
  meta?: { tip_category?: string; related_chapter?: number };
}

async function main() {
  console.log('Seeding Raseedna content (real, extracted from legacy theme)…');

  // --- Levels + Chapters + Questions + Options -----------------------------
  const chaptersData = loadJson<SeedChaptersByLevel>('chapters.json');
  // Maps the legacy "global chapter index" (1..42, level-major order) used by
  // the parent-guide extraction script to the new chapter UUID, so tips link
  // to the right chapter.
  const globalIndexToChapterId = new Map<number, string>();

  for (const levelKey of Object.keys(chaptersData).sort()) {
    const meta = LEVEL_META[levelKey];
    const level = await prisma.level.upsert({
      where: { id: `level-${levelKey}` },
      update: { title: meta.title, description: meta.description, order: Number(levelKey) },
      create: {
        id: `level-${levelKey}`,
        title: meta.title,
        description: meta.description,
        order: Number(levelKey),
      },
    });

    const chapters = chaptersData[levelKey];
    for (let i = 0; i < chapters.length; i++) {
      const ch = chapters[i];
      const globalIndex = (Number(levelKey) - 1) * 14 + i + 1;

      const chapter = await prisma.chapter.upsert({
        where: { levelId_orderInLevel: { levelId: level.id, orderInLevel: i + 1 } },
        update: {
          title: ch.title,
          description: ch.short_description,
          teaser: ch.teaser,
          icon: ch.icon,
        },
        create: {
          levelId: level.id,
          title: ch.title,
          description: ch.short_description,
          teaser: ch.teaser,
          icon: ch.icon,
          orderInLevel: i + 1,
        },
      });
      globalIndexToChapterId.set(globalIndex, chapter.id);

      // Replace this chapter's questions on every seed run (content is
      // backend-managed and re-seedable; user progress/points are untouched
      // because they key off Chapter.id / Question.id, which stay stable
      // across re-seeds as long as the chapter isn't deleted).
      await prisma.question.deleteMany({ where: { chapterId: chapter.id } });

      for (let qi = 0; qi < ch.questions.length; qi++) {
        const q = ch.questions[qi];
        const question = await prisma.question.create({
          data: {
            chapterId: chapter.id,
            text: q.text,
            explanation: q.explanation,
            points: 10,
            order: qi + 1,
          },
        });
        await prisma.answerOption.createMany({
          data: q.options.map((optText, oi) => ({
            questionId: question.id,
            optionText: optText,
            optionIndex: oi + 1,
            isCorrect: oi + 1 === q.correct,
          })),
        });
      }
    }
  }
  console.log('✓ Levels, chapters, questions, options seeded (42 chapters, real question bank).');

  // --- Financial dictionary --------------------------------------------------
  const terms = loadJson<SeedTerm[]>('dictionary.json');
  await prisma.termChapterLink.deleteMany({});
  await prisma.termRelatedLink.deleteMany({});
  await prisma.term.deleteMany({});
  for (let i = 0; i < terms.length; i++) {
    const t = terms[i];
    await prisma.term.create({
      data: {
        termName: t.term,
        explanation: t.explanation,
        category: t.category,
        icon: t.icon,
        order: i + 1,
      },
    });
  }
  console.log(`✓ ${terms.length} financial terms seeded.`);
  console.log('  NOTE: related_terms / related_chapters links were NOT present in the legacy');
  console.log('  source and are left empty for admin curation — see analysis doc §6.4.');

  // --- Parent guide -----------------------------------------------------------
  const guideTips = loadJson<Record<string, SeedGuideTip>>('parent-guide.json');
  await prisma.parentGuideEntry.deleteMany({});
  let order = 0;
  for (const tip of Object.values(guideTips)) {
    const isChapterTip = tip.meta?.tip_category === 'chapter';
    const chapterId = isChapterTip && tip.meta?.related_chapter
      ? globalIndexToChapterId.get(tip.meta.related_chapter)
      : undefined;
    await prisma.parentGuideEntry.create({
      data: {
        scope: isChapterTip ? 'chapter' : 'general',
        chapterId: chapterId ?? null,
        title: tip.title,
        content: tip.content,
        order: order++,
      },
    });
  }
  console.log(`✓ ${Object.keys(guideTips).length} parent-guide entries seeded.`);

  // --- Feature flags (safe defaults — see analysis doc §6.2) -----------------
  const defaultFlags: Record<string, boolean> = {
    ads_enabled: false, // live site currently promises parents "no ads" — do not flip without a business decision
    banner_enabled: false,
    interstitial_enabled: false,
    rewarded_enabled: false,
    billing_enabled: false, // current model: codes sold outside the app (WhatsApp/website), activated free in-app
  };
  for (const [key, value] of Object.entries(defaultFlags)) {
    await prisma.featureFlag.upsert({
      where: { key },
      update: {},
      create: { key, value },
    });
  }
  console.log('✓ Feature flags seeded with safe defaults.');

  console.log('Seeding complete.');
}

main()
  .catch((e) => {
    console.error(e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
