import { PrismaClient } from '@prisma/client';
import bcrypt from 'bcryptjs';

const prisma = new PrismaClient();
export async function seedDatabase() {
  console.log('🌱 Starting database seed...');

  try {
    // Create admin user
    const adminPassword = await bcrypt.hash('K9#mX7$vL2@n', 12);
    const admin = await prisma.user.upsert({
      where: { email: 'admin@example.com' },
      update: {
        password: adminPassword, // Actualizar contraseña en cada ejecución
      },
      create: {
        email: 'admin@example.com',
        name: 'Admin User',
        password: adminPassword,
        role: 'ADMIN',
        emailVerified: true,
      },
    });

    console.log('✅ Admin user created:', admin.email);

    // Create teacher user
    const teacherPassword = await bcrypt.hash('P3&wQ8!bR5%t', 12);
    const teacher = await prisma.user.upsert({
      where: { email: 'teacher@example.com' },
      update: {
        password: teacherPassword, // Actualizar contraseña en cada ejecución
      },
      create: {
        email: 'teacher@example.com',
        name: 'Teacher User',
        password: teacherPassword,
        role: 'TEACHER',
        emailVerified: true,
      },
    });

    console.log('✅ Teacher user created:', teacher.email);

    // Create student user
    const studentPassword = await bcrypt.hash('M6@fN9#kY2&z', 12);
    const student = await prisma.user.upsert({
      where: { email: 'student@example.com' },
      update: {
        password: studentPassword, // Actualizar contraseña en cada ejecución
      },
      create: {
        email: 'student@example.com',
        name: 'Student User',
        password: studentPassword,
        role: 'STUDENT',
        emailVerified: true,
      },
    });

    console.log('✅ Student user created:', student.email);

    // Create test bots with ElevenLabs agent IDs - all deactivated by default
    const bots = [
      {
        name: 'English Tutor Sarah',
        topic: 'General English Conversation',
        level: 'A1' as const,
        imageUrl: '',
        agentId: 'test-agent-sarah-001',
        description: 'A friendly English tutor who helps beginners practice basic conversations.',
        feedback: 'Focus on pronunciation and basic grammar. Encourage the student to speak more and correct common mistakes gently. Provide positive reinforcement for effort.',
        isActive: false, // Deactivated by default - requires connection validation to activate
      },
      {
        name: 'Business English Mike',
        topic: 'Business English',
        level: 'B1' as const,
        imageUrl: '',
        agentId: 'test-agent-mike-002',
        description: 'A professional business English coach for intermediate learners.',
        feedback: 'Emphasize professional vocabulary and formal communication. Help with business etiquette and presentation skills. Focus on clarity and confidence in business contexts.',
        isActive: false, // Deactivated by default - requires connection validation to activate
      },
      {
        name: 'Travel Guide Emma',
        topic: 'Travel English',
        level: 'A2' as const,
        imageUrl: '',
        agentId: 'test-agent-emma-003',
        description: 'A travel guide who helps you learn English for traveling and tourism.',
        feedback: 'Focus on practical travel vocabulary and common phrases. Help with booking, directions, and cultural interactions. Encourage confidence in real-world situations.',
        isActive: false, // Deactivated by default - requires connection validation to activate
      },
      {
        name: 'Academic Writing Professor',
        topic: 'Academic Writing',
        level: 'C1' as const,
        imageUrl: '',
        agentId: 'test-agent-professor-004',
        description: 'A university professor who helps with academic writing and research.',
        feedback: 'Focus on formal academic writing style, proper citations, and critical thinking. Help develop argumentation skills and academic vocabulary. Emphasize clarity and precision.',
        isActive: false, // Deactivated by default - requires connection validation to activate
      },
    ];

    console.log('🤖 Creating/updating bots...');
    for (const botData of bots) {
      try {
        const existingBot = await prisma.bot.findFirst({
          where: { name: botData.name },
        });

        if (existingBot) {
          // Check if the existing bot has a real agent ID (not a test one)
          const isTestAgentId = existingBot.agentId && existingBot.agentId.startsWith('test-agent-');
          const shouldPreserveAgentId = existingBot.agentId && !isTestAgentId;
          
          // Update existing bot, but preserve real agent IDs
          const updateData = {
            ...botData,
            // Only update agentId if the existing one is a test agent ID or null
            agentId: shouldPreserveAgentId ? existingBot.agentId : botData.agentId,
          };
          
          const bot = await prisma.bot.update({
            where: { id: existingBot.id },
            data: updateData,
          });
          
          if (shouldPreserveAgentId) {
            console.log('✅ Bot updated:', bot.name, '(preserved existing agent ID:', existingBot.agentId, ')');
          } else {
            console.log('✅ Bot updated:', bot.name, 'with agent ID:', bot.agentId);
          }
        } else {
          // Create new bot
          const bot = await prisma.bot.create({
            data: botData,
          });
          console.log('✅ Bot created:', bot.name, 'with agent ID:', bot.agentId);
        }
      } catch (error) {
        console.error('❌ Error creating/updating bot:', botData.name, error);
        throw error;
      }
    }

    // Optionally grant access to all bots for the student (controlled by env)
    const grantAll = process.env.SEED_GRANT_ALL === '1';
    if (grantAll) {
      console.log('🔐 Granting bot access to student (SEED_GRANT_ALL=1)...');
      const allBots = await prisma.bot.findMany({ where: { isActive: true } });
      
      for (const bot of allBots) {
        try {
          await prisma.studentBotAccess.upsert({
            where: {
              studentId_botId: {
                studentId: student.id,
                botId: bot.id,
              },
            },
            update: {},
            create: {
              studentId: student.id,
              botId: bot.id,
              grantedBy: teacher.id,
            },
          });

          console.log('✅ Access granted to', student.name, 'for bot:', bot.name);
        } catch (error) {
          console.error('❌ Error granting access for bot:', bot.name, error);
          throw error;
        }
      }
    } else {
      console.log('🔐 Skipping grant-all (SEED_GRANT_ALL != 1)');
    }

    // ElevenLabs configuration will be set up via admin panel
    console.log('🔧 ElevenLabs configuration will be set up via admin panel...');
    const existingConfig = await prisma.elevenLabsConfig.findFirst({
      where: { isActive: true },
    });

    if (!existingConfig) {
      console.log('ℹ️  No ElevenLabs configuration found - will be configured via admin panel');
    } else {
      console.log('✅ ElevenLabs configuration already exists');
    }

    // OpenAI configuration
    console.log('🤖 Setting up OpenAI configuration...');
    const openaiConfig = await (prisma as any).openAIConfig.upsert({
      where: { id: 'default-config' },
      update: {},
      create: {
        id: 'default-config',
        apiKey: '',
        assistantId: '',
        isActive: false
      }
    });
    console.log('✅ OpenAI configuration created');

    // Verify seeding was successful
    const botCount = await prisma.bot.count({ where: { isActive: true } });
    const userCount = await prisma.user.count();
    const accessCount = await prisma.studentBotAccess.count();

    console.log('🎉 Database seeding completed successfully!');
    console.log('📊 Verification:');
    console.log(`  - Users created: ${userCount}`);
    console.log(`  - Active bots: ${botCount}`);
    console.log(`  - Bot access grants: ${accessCount}`);
    console.log('');
    console.log('📋 Test Accounts:');
    console.log('  Admin: admin@example.com / K9#mX7$vL2@n');
    console.log('  Teacher: teacher@example.com / P3&wQ8!bR5%t');
    console.log('  Student: student@example.com / M6@fN9#kY2&z');
    console.log('');
    console.log('🤖 Test Bots (INACTIVE by default - require connection validation):');
    console.log('  - English Tutor Sarah (A1) - test-agent-sarah-001');
    console.log('  - Business English Mike (B1) - test-agent-mike-002');
    console.log('  - Travel Guide Emma (A2) - test-agent-emma-003');
    console.log('  - Academic Writing Professor (C1) - test-agent-professor-004');
    console.log('');
    console.log('⚠️  IMPORTANT: The bots are deactivated by default.');
    console.log('   To activate them, the connection with ElevenLabs will be automatically validated.');
    console.log('   If validation fails, the bots cannot be activated.');

  } catch (error) {
    console.error('❌ Error during seeding:', error);
    throw error;
  }
}

// Keep the original main function for CLI usage
async function main() {
  await seedDatabase();
}

// Only run main if this file is executed directly
if (require.main === module) {
  main()
    .catch((e) => {
      console.error('❌ Error during seeding:', e);
      process.exit(1);
    })
    .finally(async () => {
      await prisma.$disconnect();
    });
} 