import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

async function cleanup() {
  try {
    console.log('Starting cleanup of English Bible versions (keeping WEB)...')

    // Ensure WEB exists
    const web = await prisma.bibleVersion.findFirst({ where: { language: 'en', abbreviation: 'WEB' } })
    if (!web) {
      console.error('WEB version not found. Please import WEB first (via usfm-to-json + import). Aborting.')
      return
    }

    // Gather non-WEB English versions (e.g., BSB, BSB_MD, BSB_SAMPLES, etc.)
    const others = await prisma.bibleVersion.findMany({
      where: { language: 'en', NOT: { abbreviation: 'WEB' } },
      orderBy: { createdAt: 'asc' }
    })
    console.log('Found non-WEB EN versions:', others.map(v => v.abbreviation))

    for (const v of others) {
      console.log(`Deleting content for ${v.abbreviation} (${v.id}) ...`)
      // Delete verses for all chapters under this version
      const delVerses = await prisma.bibleVerse.deleteMany({
        where: { chapter: { book: { versionId: v.id } } }
      })
      console.log('  Verses deleted:', delVerses.count)

      // Delete chapters
      const delCh = await prisma.bibleChapter.deleteMany({
        where: { book: { versionId: v.id } }
      })
      console.log('  Chapters deleted:', delCh.count)

      // Delete books
      const delBooks = await prisma.bibleBook.deleteMany({ where: { versionId: v.id } })
      console.log('  Books deleted:', delBooks.count)

      // Delete version
      const delVer = await prisma.bibleVersion.delete({ where: { id: v.id } })
      console.log('  Version deleted:', delVer.abbreviation)
    }

    // Normalize defaults: set all EN isDefault=false then set WEB=true
    await prisma.bibleVersion.updateMany({ where: { language: 'en' }, data: { isDefault: false } })
    await prisma.bibleVersion.update({ where: { id: web.id }, data: { isDefault: true } })
    console.log('Set WEB as the sole default English version.')

    // Quick sanity: count WEB books
    const webBooks = await prisma.bibleBook.count({ where: { versionId: web.id } })
    console.log('WEB book count:', webBooks)
  } catch (e) {
    console.error('Cleanup failed:', e)
    process.exit(1)
  } finally {
    await prisma.$disconnect()
  }
}

cleanup()

