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;
  type?: string;
  gender?: 'm' | 'f';
}

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

async function restoreTypeAndGender() {
  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) {
    for (const yamlWord of section.words) {
      if (!yamlWord.type && !yamlWord.gender) continue;

      // 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;
      }

      const tagIdsToAdd: number[] = [];

      // Add grammar tag
      if (yamlWord.type) {
        const grammarTagId = tagMap.get(yamlWord.type.toLowerCase());
        if (grammarTagId) {
          tagIdsToAdd.push(grammarTagId);
        } else {
          console.log(`Grammar tag not found: ${yamlWord.type}`);
        }
      }

      // Add gender tag
      if (yamlWord.gender) {
        const genderName = yamlWord.gender === 'm' ? 'masculine' : 'feminine';
        const genderTagId = tagMap.get(genderName);
        if (genderTagId) {
          tagIdsToAdd.push(genderTagId);
        }
      }

      // Insert word_tags associations
      for (const tagId of tagIdsToAdd) {
        // Check if already exists
        const existing = await db
          .select()
          .from(wordTags)
          .where(and(eq(wordTags.wordId, dbWord.id), eq(wordTags.tagId, tagId)))
          .limit(1);

        if (existing.length === 0) {
          await db.insert(wordTags).values({
            wordId: dbWord.id,
            tagId: tagId,
          });
          restored++;
        }
      }
    }
  }

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

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