/**
 * 🔗 INTEGRATION SCRIPT: ENHANCED CHATBOT WITH EXISTING REMINDERS
 * 
 * This script shows how to integrate the new tree-based system
 * with the existing linear reminder system for a smooth transition.
 */

import { PrismaClient } from '@prisma/client';
import { ReminderTreeEngine, TreeBuilder } from '../lib/reminder-tree-engine';
import { scheduleReminders } from '../lib/reminders';

const prisma = new PrismaClient();

async function integrateTreesWithExistingSystem() {
  console.log('🔗 Integrating Tree System with Existing Reminders...\n');

  try {
    // Get all clinics
    const clinics = await prisma.clinic.findMany();
    
    for (const clinic of clinics) {
      console.log(`🏥 Processing clinic: ${clinic.name}`);

      // 1. Create missing trees for this clinic
      await createMissingTrees(clinic.id);

      // 2. Migrate existing appointments to tree journeys
      await migrateExistingAppointments(clinic.id);

      // 3. Update reminder templates to work with trees
      await updateReminderTemplates(clinic.id);

      console.log(`✅ Integration complete for ${clinic.name}\n`);
    }

    console.log('🎉 ALL CLINICS INTEGRATED SUCCESSFULLY!');
    console.log('\n📋 Integration Summary:');
    console.log('   ✅ Trees created for all clinics');
    console.log('   ✅ Existing appointments migrated');
    console.log('   ✅ Reminder templates updated');
    console.log('   ✅ Hybrid system ready');

  } catch (error) {
    console.error('❌ Integration failed:', error);
    throw error;
  }
}

async function createMissingTrees(clinicId: string): Promise<void> {
  const existingTrees = await prisma.reminderTree.findMany({
    where: { clinicId }
  });

  if (existingTrees.length === 0) {
    console.log('  📦 No trees found, creating standard trees...');
    
    // Create standard booking tree
    await TreeBuilder.createStandardBookingTree(clinicId);
    
    // Create other essential trees
    await createEssentialTrees(clinicId);
    
    console.log('  ✅ Essential trees created');
  } else {
    console.log(`  📦 Found ${existingTrees.length} existing trees`);
  }
}

async function createEssentialTrees(clinicId: string): Promise<void> {
  // No-show prevention tree
  const noShowTree = await prisma.reminderTree.create({
    data: {
      clinicId,
      name: 'No-Show Prevention',
      description: 'Intelligent intervention for at-risk appointments',
      triggerType: 'custom',
      isActive: true
    }
  });

  // Simple no-show prevention flow
  const noShowRoot = await prisma.treeNode.create({
    data: {
      treeId: noShowTree.id,
      name: 'Risk Assessment',
      nodeType: 'condition',
      conditions: JSON.stringify([{
        type: 'no_show_risk',
        operator: 'gt',
        value: 70
      }]),
      sortOrder: 1
    }
  });

  await prisma.treeNode.create({
    data: {
      treeId: noShowTree.id,
      parentId: noShowRoot.id,
      name: 'High Risk Intervention',
      nodeType: 'send_buttons',
      content: JSON.stringify({
        message: 'Hi {{name}}! 💙 Just checking in about your {{treatment}} appointment. Everything still looking good for {{date}}?',
        buttons: [
          { id: 'all_good', text: '✅ Yes, I\'ll be there!' },
          { id: 'need_reschedule', text: '📅 Need to reschedule' },
          { id: 'have_questions', text: '❓ I have questions' }
        ]
      }),
      conditions: JSON.stringify({ conditionResult: true }),
      sortOrder: 1
    }
  });

  console.log('  📦 No-show prevention tree created');
}

async function migrateExistingAppointments(clinicId: string): Promise<void> {
  // Find recent appointments without journeys
  const appointmentsWithoutJourneys = await prisma.appointment.findMany({
    where: {
      clinicId,
      dateTime: { gte: new Date() },
      userJourneys: { none: {} }
    },
    include: { lead: true, treatment: true },
    take: 50 // Process in batches
  });

  if (appointmentsWithoutJourneys.length === 0) {
    console.log('  📅 No appointments need migration');
    return;
  }

  console.log(`  📅 Migrating ${appointmentsWithoutJourneys.length} appointments...`);

  // Find the standard booking tree
  const bookingTree = await prisma.reminderTree.findFirst({
    where: {
      clinicId,
      triggerType: 'booking_created',
      isActive: true
    }
  });

  if (!bookingTree) {
    console.log('  ⚠️ No booking tree found, skipping migration');
    return;
  }

  for (const appointment of appointmentsWithoutJourneys) {
    try {
      // Start a journey for this appointment
      await ReminderTreeEngine.startJourney(
        appointment.id,
        bookingTree.id,
        'booking_created'
      );
      
      console.log(`    ✅ Journey started for ${appointment.lead.name}`);
    } catch (error) {
      console.log(`    ❌ Failed to start journey for ${appointment.lead.name}:`, error);
    }
  }
}

async function updateReminderTemplates(clinicId: string): Promise<void> {
  const templates = await prisma.reminderTemplate.findMany({
    where: { clinicId }
  });

  console.log(`  📝 Found ${templates.length} reminder templates`);

  // Mark traditional templates as legacy but keep them active
  // This allows for a hybrid approach during transition
  for (const template of templates) {
    const metadata = {
      isLegacy: true,
      integratedWithTrees: true,
      migrationDate: new Date().toISOString()
    };

    await prisma.reminderTemplate.update({
      where: { id: template.id },
      data: {
        // Add a note to indicate this is legacy
        message: template.message + '\n\n<!-- Legacy template - migrated to tree system -->'
      }
    });
  }

  console.log('  ✅ Templates marked as legacy');
}

// ═══════════════════════════════════════════════════════════════════
// 🎛️ HYBRID REMINDER PROCESSOR
// ═══════════════════════════════════════════════════════════════════

export async function processHybridReminders(): Promise<void> {
  console.log('🎛️ Processing Hybrid Reminder System...');

  // 1. Process tree-based reminders (new system)
  await processTreeReminders();

  // 2. Process legacy reminders (old system) - for fallback
  await processLegacyReminders();

  console.log('✅ Hybrid processing complete');
}

async function processTreeReminders(): Promise<void> {
  // Find all active journeys that need processing
  const activeJourneys = await prisma.userJourney.findMany({
    where: { status: 'active' },
    include: {
      appointment: {
        include: { clinic: true, lead: true }
      }
    },
    take: 100 // Process in batches
  });

  console.log(`📋 Processing ${activeJourneys.length} active journeys...`);

  for (const journey of activeJourneys) {
    try {
      await ReminderTreeEngine.executeNextNode(journey.id);
    } catch (error) {
      console.error(`❌ Journey ${journey.id} failed:`, error);
    }
  }
}

async function processLegacyReminders(): Promise<void> {
  // Process traditional reminders for appointments without active journeys
  const appointmentsNeedingLegacy = await prisma.appointment.findMany({
    where: {
      dateTime: { gte: new Date() },
      status: { in: ['scheduled', 'confirmed'] },
      OR: [
        { userJourneys: { none: {} } },
        { userJourneys: { every: { status: { not: 'active' } } } }
      ]
    },
    include: { clinic: true },
    take: 50
  });

  console.log(`📜 Processing ${appointmentsNeedingLegacy.length} appointments with legacy reminders...`);

  for (const appointment of appointmentsNeedingLegacy) {
    try {
      // Use traditional reminder system as fallback
      await scheduleReminders(appointment.id);
    } catch (error) {
      console.error(`❌ Legacy reminder failed for ${appointment.id}:`, error);
    }
  }
}

// ═══════════════════════════════════════════════════════════════════
// 🧪 TEST HYBRID SYSTEM
// ═══════════════════════════════════════════════════════════════════

async function testHybridSystem(): Promise<void> {
  console.log('🧪 Testing Hybrid System...\n');

  const clinic = await prisma.clinic.findFirst();
  if (!clinic) throw new Error('No clinic found');

  // Test tree system
  console.log('1️⃣ Testing Tree System...');
  const trees = await prisma.reminderTree.count({ where: { clinicId: clinic.id } });
  console.log(`   Found ${trees} trees`);

  // Test legacy system
  console.log('2️⃣ Testing Legacy System...');
  const templates = await prisma.reminderTemplate.count({ where: { clinicId: clinic.id } });
  console.log(`   Found ${templates} templates`);

  // Test hybrid processing
  console.log('3️⃣ Testing Hybrid Processing...');
  await processHybridReminders();

  console.log('✅ Hybrid system test complete');
}

// Run if this file is executed directly
if (require.main === module) {
  const action = process.argv[2];

  switch (action) {
    case 'integrate':
      integrateTreesWithExistingSystem()
        .catch(console.error)
        .finally(() => {
          prisma.$disconnect();
          process.exit(0);
        });
      break;

    case 'process':
      processHybridReminders()
        .catch(console.error)
        .finally(() => {
          prisma.$disconnect();
          process.exit(0);
        });
      break;

    case 'test':
      testHybridSystem()
        .catch(console.error)
        .finally(() => {
          prisma.$disconnect();
          process.exit(0);
        });
      break;

    default:
      console.log('Usage: npm run integrate-trees <action>');
      console.log('Actions:');
      console.log('  integrate - Integrate trees with existing system');
      console.log('  process   - Process hybrid reminders');
      console.log('  test      - Test hybrid system');
      process.exit(1);
  }
}

export { integrateTreesWithExistingSystem, testHybridSystem };