import { PrismaClient } from '../prisma/client-generated'
import { getAIProvider } from '../lib/ai/factory'
import { getSystemConfig } from '../lib/config'

const prisma = new PrismaClient()

async function regenerateAllEmbeddings() {
  console.log('🔄 Starting embedding regeneration...\n')

  // Get all notes
  const notes = await prisma.note.findMany({
    select: {
      id: true,
      title: true,
      content: true
    }
  })

  console.log(`📝 Found ${notes.length} notes to process\n`)

  // Get AI provider
  const config = await getSystemConfig()
  const provider = getAIProvider(config)

  console.log(`🤖 Using AI provider...`)

  let successCount = 0
  let errorCount = 0

  for (const note of notes) {
    try {
      const title = note.title || '(no title)'
      process.stdout.write(`\r⏳ Processing ${successCount + 1}/${notes.length}: ${title.substring(0, 40)}...`)

      // Generate new embedding
      const embedding = await provider.getEmbeddings(note.content)

      if (embedding) {
        // Update note with new embedding
        await prisma.note.update({
          where: { id: note.id },
          data: {
            embedding
          }
        })

        successCount++
      } else {
        errorCount++
        console.log(`\n❌ Failed: ${title} (no embedding generated)`)
      }
    } catch (error) {
      errorCount++
      const errorMessage = error instanceof Error ? error.message : 'Unknown error'
      console.log(`\n❌ Error: ${note.title || '(no title)'} - ${errorMessage}`)
    }
  }

  console.log(`\n\n📊 Summary:`)
  console.log(`  ✅ Success: ${successCount}/${notes.length}`)
  console.log(`  ❌ Errors: ${errorCount}/${notes.length}`)
  console.log('\n✨ Embeddings regenerated successfully!')

  await prisma.$disconnect()
}

regenerateAllEmbeddings().catch(console.error)
