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

const prisma = new PrismaClient()

async function main() {
  try {
    const abbr = (process.env.EN_ABBR || 'WEB').toUpperCase()
    const lang = 'en'
    const dir = process.env.INPUT_DIR || path.join('data', 'en_bible', abbr)
    if (!fs.existsSync(path.join(dir, 'old_testament.json')) || !fs.existsSync(path.join(dir, 'new_testament.json'))) {
      console.error('Missing OT/NT JSON in', dir)
      process.exit(1)
    }

    // Ensure version exists
    let version = await prisma.bibleVersion.findUnique({ where: { abbreviation_language: { abbreviation: abbr, language: lang } } })
    if (!version) {
      version = await prisma.bibleVersion.create({ data: { name: abbr, abbreviation: abbr, language: lang, description: `English Bible (${abbr})`, isDefault: true } })
      console.log('Created version', version.id)
    } else {
      // Make this the default and disable others
      await prisma.bibleVersion.updateMany({ where: { language: lang }, data: { isDefault: false } })
      await prisma.bibleVersion.update({ where: { id: version.id }, data: { isDefault: true } })
    }

    // Wipe current WEB content for a clean import
    const delVerses = await prisma.bibleVerse.deleteMany({ where: { chapter: { book: { versionId: version.id } } } })
    console.log('Deleted verses for', abbr, ':', delVerses.count)

  } catch (e) {
    console.error('Reset failed:', e)
    process.exit(1)
  } finally {
    await prisma.$disconnect()
  }
}

main()
