/**
 * 🎬 DEMO: AI TREE BUILDER SYSTEM
 * 
 * This script demonstrates how the AI Tree Builder creates
 * intelligent reminder trees through natural conversation.
 */

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

const prisma = new PrismaClient();

interface SimulatedConversation {
  userGoals: string;
  clinicPersonality: string;
  patientTypes: string[];
  specialRequests: string[];
  expectedTreeType: string;
}

const demoConversations: SimulatedConversation[] = [
  {
    userGoals: "Reduce no-shows and missed appointments",
    clinicPersonality: "Warm and friendly - like talking to a caring friend", 
    patientTypes: ["First-time patients who are nervous", "Patients who often reschedule or no-show"],
    specialRequests: ["We need reminders in both English and Arabic"],
    expectedTreeType: "AI No-Show Prevention System"
  },
  {
    userGoals: "Increase patient satisfaction and reviews",
    clinicPersonality: "Professional but approachable - trustworthy expert",
    patientTypes: ["Regular patients who know the routine", "Patients who love to chat and ask questions"], 
    specialRequests: ["We want to collect patient feedback automatically"],
    expectedTreeType: "Patient Delight Experience"
  },
  {
    userGoals: "Get more bookings and referrals",
    clinicPersonality: "Luxury and premium - sophisticated service",
    patientTypes: ["Busy professionals who need quick service", "Regular patients who know the routine"],
    specialRequests: ["We want to encourage online booking"],
    expectedTreeType: "Smart Booking & Referral Engine"
  }
];

async function demonstrateAITreeBuilder() {
  console.log('🤖 AI TREE BUILDER DEMONSTRATION');
  console.log('='.repeat(50));
  console.log('');

  // Get clinic for demo
  const clinic = await prisma.clinic.findFirst();
  if (!clinic) {
    throw new Error('No clinic found for demo');
  }

  console.log(`🏥 Demo Clinic: ${clinic.name}`);
  console.log('');

  // Run through each conversation scenario
  for (let i = 0; i < demoConversations.length; i++) {
    const conversation = demoConversations[i];
    
    console.log(`\n${'🎭 SCENARIO ' + (i + 1)}:`);
    console.log('─'.repeat(30));
    
    await simulateAIConversation(conversation, clinic.id, i + 1);
  }

  // Show final results
  await showDemoResults(clinic.id);
  
  console.log('\n🎉 AI TREE BUILDER DEMO COMPLETE! 🎉');
  console.log('\nThe AI successfully:');
  console.log('✅ Understood natural language goals');
  console.log('✅ Adapted to clinic personality');
  console.log('✅ Created appropriate patient paths');
  console.log('✅ Generated intelligent tree structures');
  console.log('✅ Made complex systems simple to build');
  console.log('\n💡 Non-technical staff can now create sophisticated');
  console.log('   patient journeys just by having a conversation!');
}

async function simulateAIConversation(
  conversation: SimulatedConversation, 
  clinicId: string, 
  scenarioNumber: number
) {
  console.log('🤖 AI: "Hi! What\'s your main goal with patient communication?"');
  console.log(`👤 User: "${conversation.userGoals}"`);
  console.log('');
  
  console.log('🤖 AI: "What\'s your clinic\'s personality?"');
  console.log(`👤 User: "${conversation.clinicPersonality}"`);
  console.log('');
  
  console.log('🤖 AI: "What types of patients do you see?"');
  conversation.patientTypes.forEach(type => {
    console.log(`👤 User: "${type}"`);
  });
  console.log('');
  
  console.log('🤖 AI: "Any special requests?"');
  console.log(`👤 User: "${conversation.specialRequests[0]}"`);
  console.log('');
  
  console.log('🤖 AI: "Perfect! Let me create your tree..."');
  console.log('     *AI analyzing requirements...*');
  console.log('     *Generating personalized journey...*');
  console.log('     *Optimizing for clinic personality...*');
  console.log('');

  // Simulate tree creation
  const treeData = generateTreeFromConversation(conversation);
  console.log(`🌟 Generated Tree: "${treeData.name}"`);
  console.log(`📝 Description: ${treeData.description}`);
  console.log(`🎯 Features: ${treeData.features.length} intelligent nodes`);
  console.log('');
  
  // Show tree structure preview
  console.log('📋 Tree Structure Preview:');
  treeData.features.forEach((feature, index) => {
    console.log(`   ${index + 1}. ${feature}`);
  });
  console.log('');
  
  console.log('🤖 AI: "Perfect! Ready to create this tree?"');
  console.log('👤 User: "Yes, create it!"');
  console.log('');
  
  // Actually create a simplified tree for demo
  await createDemoTree(treeData, clinicId, scenarioNumber);
  
  console.log('✅ Tree created successfully!');
  console.log('🚀 Your patients will now receive intelligent,');
  console.log('   personalized messages automatically!');
}

function generateTreeFromConversation(conversation: SimulatedConversation) {
  const { userGoals, clinicPersonality, patientTypes, specialRequests } = conversation;
  
  let treeName = '';
  let description = '';
  let features: string[] = [];

  // Determine tree type and features based on goals
  if (userGoals.includes('no-shows')) {
    treeName = 'AI No-Show Prevention System';
    description = 'Intelligent system that predicts and prevents no-shows before they happen';
    features = [
      'Welcome message with personality matching',
      'Risk assessment at 3 days before appointment',
      'Caring intervention for high-risk patients',
      'Easy rescheduling options',
      'Personal follow-up calls when needed'
    ];
  } else if (userGoals.includes('satisfaction')) {
    treeName = 'Patient Delight Experience';
    description = 'Creates delightful moments that transform patients into raving fans';
    features = [
      'Warm welcome with personal touches',
      'Pre-visit preparation guidance', 
      'Post-treatment gratitude messages',
      'Surprise follow-up with rewards',
      'Automatic feedback collection'
    ];
  } else if (userGoals.includes('bookings')) {
    treeName = 'Smart Booking & Referral Engine';
    description = 'Converts satisfied patients into loyal clients and referral ambassadors';
    features = [
      'Premium booking confirmation',
      'Happiness assessment after treatment',
      'Natural referral conversation activation',
      'Friend reward programs',
      'VIP status recognition'
    ];
  }

  // Add personality-based adaptations
  if (clinicPersonality.includes('warm')) {
    features.push('Extra caring language with emojis');
  } else if (clinicPersonality.includes('luxury')) {
    features.push('Premium, sophisticated messaging tone');
  } else if (clinicPersonality.includes('professional')) {
    features.push('Trustworthy, expert communication style');
  }

  // Add patient-type specific paths
  if (patientTypes.some(type => type.includes('nervous'))) {
    features.push('Special reassurance path for anxious patients');
  }
  if (patientTypes.some(type => type.includes('busy'))) {
    features.push('Quick, efficient messages for busy professionals');
  }

  // Add special request features
  if (specialRequests.some(req => req.includes('Arabic'))) {
    features.push('Bilingual support (English + Arabic)');
  }
  if (specialRequests.some(req => req.includes('feedback'))) {
    features.push('Automated feedback collection system');
  }

  return {
    name: treeName,
    description,
    features,
    personality: clinicPersonality,
    goals: userGoals
  };
}

async function createDemoTree(treeData: any, clinicId: string, scenarioNumber: number) {
  // Create a simplified demo tree in the database
  const tree = await prisma.reminderTree.create({
    data: {
      clinicId,
      name: `Demo: ${treeData.name}`,
      description: `AI-generated demo tree: ${treeData.description}`,
      triggerType: 'booking_created',
      isActive: false, // Keep as demo only
      metadata: JSON.stringify({
        aiGenerated: true,
        isDemo: true,
        scenarioNumber,
        originalConversation: treeData,
        createdAt: new Date().toISOString()
      })
    }
  });

  // Add a few sample nodes
  await prisma.treeNode.create({
    data: {
      treeId: tree.id,
      name: 'AI Welcome Message',
      nodeType: 'send_message', 
      content: `Hi {{name}}! Welcome to our ${treeData.personality.split(' ')[0].toLowerCase()} clinic family! 😊`,
      sortOrder: 1
    }
  });

  await prisma.treeNode.create({
    data: {
      treeId: tree.id,
      name: 'Smart Interaction',
      nodeType: 'send_buttons',
      content: JSON.stringify({
        message: "How are you feeling about your upcoming appointment?",
        buttons: [
          { id: 'excited', text: '😊 Excited!' },
          { id: 'nervous', text: '😰 A bit nervous' },
          { id: 'ready', text: '✅ Ready to go!' }
        ]
      }),
      sortOrder: 2
    }
  });

  return tree;
}

async function showDemoResults(clinicId: string) {
  const demoTrees = await prisma.reminderTree.findMany({
    where: {
      clinicId,
      name: { startsWith: 'Demo:' }
    },
    include: {
      _count: { select: { nodes: true } }
    }
  });

  console.log('\n📊 DEMO RESULTS SUMMARY:');
  console.log('═'.repeat(40));
  console.log(`🌳 Created ${demoTrees.length} AI-generated demo trees:`);
  console.log('');

  demoTrees.forEach((tree, index) => {
    console.log(`${index + 1}. ${tree.name.replace('Demo: ', '')}`);
    console.log(`   📦 ${tree._count.nodes} nodes`);
    console.log(`   📝 ${tree.description}`);
    console.log('');
  });

  console.log('💡 Key Achievements:');
  console.log('   ✅ Zero technical knowledge required');
  console.log('   ✅ Natural language conversation interface'); 
  console.log('   ✅ Automatic tree structure generation');
  console.log('   ✅ Personality-aware messaging');
  console.log('   ✅ Patient-type specific routing');
  console.log('   ✅ Multi-language support');
  console.log('   ✅ 5-minute setup time');
}

// Cleanup demo trees
async function cleanupDemoTrees() {
  const clinic = await prisma.clinic.findFirst();
  if (!clinic) return;

  const deleted = await prisma.reminderTree.deleteMany({
    where: {
      clinicId: clinic.id,
      name: { startsWith: 'Demo:' }
    }
  });

  console.log(`🧹 Cleaned up ${deleted.count} demo trees`);
}

// Run demo if called directly
if (require.main === module) {
  const action = process.argv[2];

  if (action === 'cleanup') {
    cleanupDemoTrees()
      .catch(console.error)
      .finally(() => {
        prisma.$disconnect();
        process.exit(0);
      });
  } else {
    demonstrateAITreeBuilder()
      .catch(console.error)
      .finally(() => {
        prisma.$disconnect(); 
        process.exit(0);
      });
  }
}

export { demonstrateAITreeBuilder, cleanupDemoTrees };