import fs from 'fs/promises';
import path from 'path';
import YAML from 'yaml';
import { db } from '../src/lib/db';
import { words, examples, tags, wordTags, seeAlso } from '../src/lib/db/schema';

interface YAMLWord {
  english: string;
  hindi: string;
  type?: string;
  gender?: string;
  note?: string;
  examples?: Array<{
    english: string;
    hindi: string;
    note?: string;
  }>;
  see_also?: string[];
}

interface YAMLCategory {
  slug: string;
  about: string;
  words: YAMLWord[];
}

async function migrate() {
  try {
    // Read YAML file
    const yamlPath = path.join(process.cwd(), 'src', 'vocab_list.yaml');
    const content = await fs.readFile(yamlPath, 'utf-8');
    const categories: YAMLCategory[] = YAML.parse(content);

    console.log(`Found ${categories.length} categories`);

    // Create tags from categories
    const tagMap = new Map<string, number>();

    for (const category of categories) {
      const [tag] = await db.insert(tags)
        .values({
          name: category.slug,
          description: category.about,
        })
        .returning();

      tagMap.set(category.slug, tag.id);
      console.log(`Created tag: ${category.slug}`);
    }

    // Migrate words
    let wordCount = 0;
    for (const category of categories) {
      const tagId = tagMap.get(category.slug)!;

      for (const yamlWord of category.words) {
        // Insert word
        const [word] = await db.insert(words)
          .values({
            hindi: yamlWord.hindi,
            english: yamlWord.english,
            type: yamlWord.type || null,
            gender: yamlWord.gender || null,
            note: yamlWord.note || null,
          })
          .returning();

        // Associate with tag
        await db.insert(wordTags).values({
          wordId: word.id,
          tagId: tagId,
        });

        // Insert examples
        if (yamlWord.examples) {
          for (const example of yamlWord.examples) {
            await db.insert(examples).values({
              wordId: word.id,
              hindi: example.hindi,
              english: example.english,
              note: example.note || null,
            });
          }
        }

        // Insert see_also references
        if (yamlWord.see_also) {
          for (const reference of yamlWord.see_also) {
            await db.insert(seeAlso).values({
              wordId: word.id,
              reference: reference,
              note: null,
            });
          }
        }

        wordCount++;
      }
    }

    console.log(`\nMigration complete!`);
    console.log(`- Created ${tagMap.size} tags`);
    console.log(`- Migrated ${wordCount} words`);

  } catch (error) {
    console.error('Migration failed:', error);
    process.exit(1);
  }
}

migrate();
