import { readFileSync } from 'fs';
import { parse } from 'yaml';
import { db } from '../src/lib/db';
import { words, tags, wordTags } from '../src/lib/db/schema';
import { eq, and } from 'drizzle-orm';

interface YAMLWord {
  hindi: string;
  english: string;
}

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

async function restorePageTags() {
  const yamlContent = readFileSync('./src/vocab_list.yaml', 'utf-8');
  const sections: YAMLSection[] = parse(yamlContent);

  // Get all tag IDs
  const allTags = await db.select().from(tags);
  const tagMap = new Map(allTags.map(t => [t.name.toLowerCase(), t.id]));

  let restored = 0;
  let notFound = 0;

  for (const section of sections) {
    console.log(`Processing section: ${section.slug} with ${section.words.length} words`);
    const pageTagId = tagMap.get(section.slug.toLowerCase());

    if (!pageTagId) {
      console.log(`Page tag not found: ${section.slug}`);
      continue;
    }

    console.log(`Found page tag ID: ${pageTagId} for ${section.slug}`);

    for (const yamlWord of section.words) {
      // Find the word in DB by hindi text
      const [dbWord] = await db
        .select()
        .from(words)
        .where(eq(words.hindi, yamlWord.hindi))
        .limit(1);

      if (!dbWord) {
        console.log(`Word not found: ${yamlWord.hindi} (${yamlWord.english})`);
        notFound++;
        continue;
      }

      // Check if page tag association already exists
      const existing = await db
        .select()
        .from(wordTags)
        .where(and(eq(wordTags.wordId, dbWord.id), eq(wordTags.tagId, pageTagId)))
        .limit(1);

      if (existing.length === 0) {
        await db.insert(wordTags).values({
          wordId: dbWord.id,
          tagId: pageTagId,
        });
        restored++;
        console.log(`Added ${section.slug} tag to: ${yamlWord.hindi}`);
      }
    }
  }

  console.log(`\nRestoration complete!`);
  console.log(`Page tags added: ${restored}`);
  console.log(`Words not found: ${notFound}`);
}

restorePageTags()
  .then(() => process.exit(0))
  .catch((err) => {
    console.error(err);
    process.exit(1);
  });
