import { PrismaClient } from '@prisma/client'
import fs from 'fs'
import path from 'path'

const prisma = new PrismaClient()

interface BibleData {
  testament: string;
  books: Array<{
    name: string;
    chapters: Array<{
      chapterNum: number;
      verses: Array<{
        verseNum: number;
        text: string;
      }>;
    }>;
  }>;
}

function getBookKey(bookName: string): string {
  const keyMap: Record<string, string> = {
    'Geneza': 'genesis',
    'Exodul': 'exodus',
    'Leviticul': 'leviticus',
    'Numerii': 'numbers',
    'Deuteronomul': 'deuteronomy',
    'Iosua': 'joshua',
    'Judecătorii': 'judges',
    'Rut': 'ruth',
    '1 Samuel': '1_samuel',
    '2 Samuel': '2_samuel',
    '1 Împăraţi': '1_kings',
    '2 Împăraţi': '2_kings',
    '1 Cronici': '1_chronicles',
    '2 Cronici': '2_chronicles',
    'Ezra': 'ezra',
    'Neemia': 'nehemiah',
    'Estera': 'esther',
    'Iov': 'job',
    'Psalmii': 'psalms',
    'Proverbele': 'proverbs',
    'Ecclesiastul': 'ecclesiastes',
    'Cântarea Cântărilor': 'song_of_songs',
    'Isaia': 'isaiah',
    'Ieremia': 'jeremiah',
    'Plângerile lui Ieremia': 'lamentations',
    'Ezechiel': 'ezekiel',
    'Daniel': 'daniel',
    'Osea': 'hosea',
    'Ioel': 'joel',
    'Amos': 'amos',
    'Obadia': 'obadiah',
    'Iona': 'jonah',
    'Mica': 'micah',
    'Naum': 'nahum',
    'Habacuc': 'habakkuk',
    'Ţefania': 'zephaniah',
    'Hagai': 'haggai',
    'Zaharia': 'zechariah',
    'Maleahi': 'malachi',
    'Matei': 'matthew',
    'Marcu': 'mark',
    'Luca': 'luke',
    'Ioan': 'john',
    'Faptele Apostolilor': 'acts',
    'Romani': 'romans',
    '1 Corinteni': '1_corinthians',
    '2 Corinteni': '2_corinthians',
    'Galateni': 'galatians',
    'Efeseni': 'ephesians',
    'Filipeni': 'philippians',
    'Coloseni': 'colossians',
    '1 Tesaloniceni': '1_thessalonians',
    '2 Tesaloniceni': '2_thessalonians',
    '1 Timotei': '1_timothy',
    '2 Timotei': '2_timothy',
    'Tit': 'titus',
    'Filimon': 'philemon',
    'Evrei': 'hebrews',
    'Iacov': 'james',
    '1 Petru': '1_peter',
    '2 Petru': '2_peter',
    '1 Ioan': '1_john',
    '2 Ioan': '2_john',
    '3 Ioan': '3_john',
    'Iuda': 'jude',
    'Apocalipsa': 'revelation',
    'Revelaţia': 'revelation',
    'Revelația': 'revelation',
    'Numeri': 'numbers',
    'Deuteronom': 'deuteronomy',
    'Judecători': 'judges',
    '1 Imparati': '1_kings',
    '2 Imparati': '2_kings',
    'Proverbe': 'proverbs',
    'Țefania': 'zephaniah'
  }

  return keyMap[bookName] || bookName.toLowerCase().replace(/\s+/g, '_')
}

async function importRomanianBible() {
  console.log('Starting Romanian Bible import with versioned schema...')

  try {
    // Step 1: Create Romanian Bible version
    console.log('Creating Romanian Bible version...')
    const romanianVersion = await prisma.bibleVersion.upsert({
      where: {
        abbreviation_language: {
          abbreviation: 'CORNILESCU',
          language: 'ro'
        }
      },
      update: {},
      create: {
        name: 'Biblia Cornilescu',
        abbreviation: 'CORNILESCU',
        language: 'ro',
        description: 'Traducerea Cornilescu a Bibliei în limba română',
        isDefault: true
      }
    })

    console.log(`Created Romanian version: ${romanianVersion.id}`)

    // Step 1.1: Clear any existing Romanian content for this version (idempotent import)
    console.log('Clearing existing Romanian version content (if any)...')
    await prisma.bibleVerse.deleteMany({
      where: { chapter: { book: { versionId: romanianVersion.id } } }
    })
    await prisma.bibleChapter.deleteMany({
      where: { book: { versionId: romanianVersion.id } }
    })
    await prisma.bibleBook.deleteMany({ where: { versionId: romanianVersion.id } })

    // Step 2: Import Old Testament
    console.log('Importing Old Testament...')
    const otPath = path.join(process.cwd(), 'data', 'old_testament.json')
    if (fs.existsSync(otPath)) {
      const otData: BibleData = JSON.parse(fs.readFileSync(otPath, 'utf-8'))
      await importTestament(romanianVersion.id, otData, 'Old Testament')
    } else {
      console.log('Old Testament data file not found, skipping...')
    }

    // Step 3: Import New Testament
    console.log('Importing New Testament...')
    const ntPath = path.join(process.cwd(), 'data', 'new_testament.json')
    if (fs.existsSync(ntPath)) {
      const ntData: BibleData = JSON.parse(fs.readFileSync(ntPath, 'utf-8'))
      await importTestament(romanianVersion.id, ntData, 'New Testament')
    } else {
      console.log('New Testament data file not found, skipping...')
    }

    console.log('Romanian Bible import completed successfully!')

  } catch (error) {
    console.error('Error importing Romanian Bible:', error)
    throw error
  }
}

async function importTestament(versionId: string, testamentData: BibleData, testament: string) {
  console.log(`Importing ${testament}...`)

  let orderNum = testament === 'Old Testament' ? 1 : 40

  for (const bookData of testamentData.books) {
    console.log(`  Processing ${bookData.name}...`)

    const bookKey = getBookKey(bookData.name)

    // Create book
    const book = await prisma.bibleBook.create({
      data: {
        versionId,
        name: bookData.name,
        testament,
        orderNum,
        bookKey
      }
    })

    // Import chapters
    for (const chapterData of bookData.chapters) {
      console.log(`    Chapter ${chapterData.chapterNum}...`)

      // Create chapter
      const chapter = await prisma.bibleChapter.create({
        data: {
          bookId: book.id,
          chapterNum: chapterData.chapterNum
        }
      })

      // Import verses (dedupe by verseNum, then bulk insert with skipDuplicates)
      const uniqueByVerse: Record<number, { verseNum: number; text: string }> = {}
      for (const v of chapterData.verses) {
        uniqueByVerse[v.verseNum] = { verseNum: v.verseNum, text: v.text }
      }
      const versesData = Object.values(uniqueByVerse).map(v => ({
        chapterId: chapter.id,
        verseNum: v.verseNum,
        text: v.text
      }))
      if (versesData.length > 0) {
        await prisma.bibleVerse.createMany({ data: versesData, skipDuplicates: true })
      }

      console.log(`      Imported ${chapterData.verses.length} verses`)
    }

    orderNum++
  }
}

// Run the import
importRomanianBible()
  .then(() => {
    console.log('Romanian Bible import completed successfully!')
    process.exit(0)
  })
  .catch((error) => {
    console.error('Import failed:', error)
    process.exit(1)
  })
  .finally(() => prisma.$disconnect())
