import 'dotenv/config';
import * as fs from 'fs';
import * as path from 'path';
import { PrismaClient } from '../src/generated/prisma/client.js';
import { PrismaPg } from '@prisma/adapter-pg';

const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL });
const prisma = new PrismaClient({ adapter });

interface EquipmentLevel {
  name: string;
  level: string;
}

async function updateEquipmentLevels() {
  // Read the JSON file from prisma/data
  const dataPath = path.join(__dirname, 'data', 'equipmentlevel.json');

  if (!fs.existsSync(dataPath)) {
    console.error('❌ equipmentlevel.json not found at:', dataPath);
    process.exit(1);
  }

  const data: EquipmentLevel[] = JSON.parse(fs.readFileSync(dataPath, 'utf-8'));
  console.log(`📦 Found ${data.length} equipment entries with levels`);

  let updated = 0;
  let notFound = 0;
  let errors = 0;

  // Process in batches for better performance
  const batchSize = 100;
  for (let i = 0; i < data.length; i += batchSize) {
    const batch = data.slice(i, i + batchSize);

    await Promise.all(
      batch.map(async (item) => {
        try {
          // Parse level - handle "-1", "0", "1", etc.
          const level = parseInt(item.level, 10);
          if (isNaN(level)) {
            console.warn(`⚠️  Invalid level for "${item.name}": ${item.level}`);
            errors++;
            return;
          }

          // Update equipment by name
          const result = await prisma.equipment.updateMany({
            where: { name: item.name },
            data: { level },
          });

          if (result.count > 0) {
            updated++;
          } else {
            // Try case-insensitive search
            const equipment = await prisma.equipment.findFirst({
              where: {
                name: {
                  equals: item.name,
                  mode: 'insensitive',
                },
              },
            });

            if (equipment) {
              await prisma.equipment.update({
                where: { id: equipment.id },
                data: { level },
              });
              updated++;
            } else {
              notFound++;
            }
          }
        } catch (err) {
          console.error(`❌ Error updating "${item.name}":`, err);
          errors++;
        }
      })
    );

    // Progress update
    const progress = Math.min(i + batchSize, data.length);
    process.stdout.write(`\r⏳ Processing: ${progress}/${data.length} (${Math.round(progress / data.length * 100)}%)`);
  }

  console.log('\n');
  console.log('✅ Update complete!');
  console.log(`   Updated: ${updated}`);
  console.log(`   Not found in DB: ${notFound}`);
  console.log(`   Errors: ${errors}`);
}

async function main() {
  console.log('🔄 Updating equipment levels from equipmentlevel.json...\n');

  try {
    await updateEquipmentLevels();
  } catch (error) {
    console.error('Fatal error:', error);
    process.exit(1);
  } finally {
    await prisma.$disconnect();
  }
}

main();
