/**
 * 🎬 DEMO: CREATE IMPRESSIVE REMINDER TREES
 * 
 * This script creates sophisticated, real-world reminder trees
 * that showcase the power of the AI-driven system.
 */

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

const prisma = new PrismaClient();

// ═══════════════════════════════════════════════════════════════════
// 🌟 PREMIUM BOOKING EXPERIENCE TREE
// ═══════════════════════════════════════════════════════════════════

async function createPremiumBookingTree(clinicId: string): Promise<void> {
  console.log('🌟 Creating Premium Booking Experience Tree...');

  const tree = await prisma.reminderTree.create({
    data: {
      clinicId,
      name: 'Premium Booking Experience',
      description: 'AI-powered luxury booking journey with personalized touches',
      triggerType: 'booking_created',
      version: 1,
      metadata: JSON.stringify({
        tags: ['premium', 'personalized', 'luxury'],
        targetSegment: 'high_value_clients'
      })
    }
  });

  // Root: Welcome & Immediate Confirmation
  const root = await prisma.treeNode.create({
    data: {
      treeId: tree.id,
      name: 'Premium Welcome',
      nodeType: 'send_message',
      content: `🌟 Welcome to {{clinic}}, {{name}}!

Your {{treatment}} appointment is confirmed:
📅 {{date}} at {{time}}

We're preparing something special for your visit! ✨

Our premium concierge will send you personalized pre-visit details shortly.`,
      offsetMinutes: 0,
      sortOrder: 1
    }
  });

  // Wait 10 minutes for processing
  const wait1 = await prisma.treeNode.create({
    data: {
      treeId: tree.id,
      parentId: root.id,
      name: 'Processing Wait',
      nodeType: 'wait',
      offsetMinutes: 10,
      sortOrder: 1
    }
  });

  // Personalized experience selector
  const experienceSelector = await prisma.treeNode.create({
    data: {
      treeId: tree.id,
      parentId: wait1.id,
      name: 'Experience Customization',
      nodeType: 'send_buttons',
      content: JSON.stringify({
        message: `{{name}}, let's customize your experience! 🎯

Based on your {{treatment}}, we can enhance your visit:`,
        buttons: [
          { id: 'premium_prep', text: '✨ Premium Prep Package' },
          { id: 'relaxation', text: '🧘‍♀️ Pre-visit Relaxation' },
          { id: 'express', text: '⚡ Express Service' },
          { id: 'surprise', text: '🎁 Surprise Me!' }
        ]
      }),
      sortOrder: 1
    }
  });

  // Branch 1: Premium Prep Package
  const premiumPrep = await prisma.treeNode.create({
    data: {
      treeId: tree.id,
      parentId: experienceSelector.id,
      name: 'Premium Prep Path',
      nodeType: 'send_message',
      content: `Perfect choice, {{name}}! 🌟

Your Premium Prep Package includes:
✨ Detailed preparation guide delivered today
🍃 Complimentary prep kit delivered to your door
📱 Direct line to our prep specialist
💎 VIP arrival experience

We'll send your prep materials within 24 hours. Any questions? Just reply!`,
      conditions: JSON.stringify({ keywords: ['premium_prep'] }),
      sortOrder: 1
    }
  });

  // Branch 2: Relaxation Path
  const relaxationPath = await prisma.treeNode.create({
    data: {
      treeId: tree.id,
      parentId: experienceSelector.id,
      name: 'Relaxation Path',
      nodeType: 'send_buttons',
      content: JSON.stringify({
        message: `Wonderful! Let's create your zen experience 🧘‍♀️

Which relaxation approach speaks to you?`,
        buttons: [
          { id: 'meditation', text: '🧘‍♀️ Guided Meditation' },
          { id: 'music', text: '🎵 Curated Playlist' },
          { id: 'aromatherapy', text: '🌸 Aromatherapy Guide' }
        ]
      }),
      conditions: JSON.stringify({ keywords: ['relaxation'] }),
      sortOrder: 2
    }
  });

  // Add 3-day before reminder with risk assessment
  const threeDayReminder = await prisma.treeNode.create({
    data: {
      treeId: tree.id,
      parentId: premiumPrep.id,
      name: '3-Day Risk Assessment',
      nodeType: 'condition',
      conditions: JSON.stringify([
        {
          type: 'no_show_risk',
          operator: 'gt',
          value: 70,
          weight: 0.6
        },
        {
          type: 'engagement_score',
          operator: 'lt',
          value: 40,
          weight: 0.4
        }
      ]),
      offsetMinutes: 4320, // 3 days
      sortOrder: 1
    }
  });

  // High risk path - extra attention
  const highRiskPath = await prisma.treeNode.create({
    data: {
      treeId: tree.id,
      parentId: threeDayReminder.id,
      name: 'High Risk VIP Care',
      nodeType: 'send_buttons',
      content: JSON.stringify({
        message: `Hi {{name}}! 💎 Your premium {{treatment}} is in 3 days.

As a valued client, we want to ensure everything is perfect for you:`,
        buttons: [
          { id: 'personal_call', text: '📞 Personal Consultation Call' },
          { id: 'reschedule_easy', text: '📅 Easy Reschedule Option' },
          { id: 'all_set', text: '✅ I\'m All Set!' }
        ]
      }),
      conditions: JSON.stringify({ conditionResult: true }),
      sortOrder: 1
    }
  });

  // Low risk path - confidence booster
  const lowRiskPath = await prisma.treeNode.create({
    data: {
      treeId: tree.id,
      parentId: threeDayReminder.id,
      name: 'Confidence Booster',
      nodeType: 'send_message',
      content: `Hi {{name}}! 🌟 Just 3 days until your premium {{treatment}}!

Everything is prepared and ready for your arrival. You're in excellent hands with our award-winning team.

Looking forward to providing you with an exceptional experience! ✨`,
      conditions: JSON.stringify({ conditionResult: false }),
      sortOrder: 2
    }
  });

  console.log('✅ Premium Booking Experience Tree created');
}

// ═══════════════════════════════════════════════════════════════════
// 🎯 SMART NO-SHOW PREVENTION TREE
// ═══════════════════════════════════════════════════════════════════

async function createNoShowPreventionTree(clinicId: string): Promise<void> {
  console.log('🎯 Creating Smart No-Show Prevention Tree...');

  const tree = await prisma.reminderTree.create({
    data: {
      clinicId,
      name: 'AI No-Show Prevention System',
      description: 'Predictive intervention system that prevents no-shows before they happen',
      triggerType: 'custom',
      version: 1,
      metadata: JSON.stringify({
        tags: ['ai_powered', 'predictive', 'intervention'],
        triggerConditions: ['high_no_show_risk', 'engagement_drop']
      })
    }
  });

  // Root: Risk Assessment
  const root = await prisma.treeNode.create({
    data: {
      treeId: tree.id,
      name: 'Risk Assessment Scanner',
      nodeType: 'condition',
      conditions: JSON.stringify([
        {
          type: 'no_show_risk',
          operator: 'gt',
          value: 60,
          weight: 0.4
        },
        {
          type: 'engagement_score',
          operator: 'lt',
          value: 30,
          weight: 0.3
        },
        {
          type: 'response_time',
          operator: 'gt',
          value: 120, // 2 hours average response time
          weight: 0.3
        }
      ]),
      offsetMinutes: 0,
      sortOrder: 1
    }
  });

  // High Risk: Immediate Intervention
  const immediateIntervention = await prisma.treeNode.create({
    data: {
      treeId: tree.id,
      parentId: root.id,
      name: 'Immediate Care Intervention',
      nodeType: 'send_buttons',
      content: JSON.stringify({
        message: `Hi {{name}}! 💙 We noticed you might be having second thoughts about your upcoming {{treatment}}.

That's completely normal! Let's make sure you feel 100% confident:`,
        buttons: [
          { id: 'talk_concerns', text: '💬 Discuss My Concerns' },
          { id: 'different_time', text: '🕐 Find Better Time' },
          { id: 'more_info', text: 'ℹ️ More Information' },
          { id: 'im_good', text: '✅ I\'m Good, Thanks!' }
        ]
      }),
      conditions: JSON.stringify({ conditionResult: true }),
      sortOrder: 1
    }
  });

  // Concern Discussion Path
  const concernPath = await prisma.treeNode.create({
    data: {
      treeId: tree.id,
      parentId: immediateIntervention.id,
      name: 'Concern Collection',
      nodeType: 'collect_input',
      content: JSON.stringify({
        inputType: 'text',
        prompt: `I understand your concerns, {{name}}. 💭

Please share what's on your mind - whether it's about the procedure, timing, cost, or anything else. Our specialist will personally address each concern.

What would you like to discuss?`
      }),
      conditions: JSON.stringify({ keywords: ['talk_concerns', 'concerns'] }),
      sortOrder: 1
    }
  });

  // Follow-up after concern collection
  const concernFollowup = await prisma.treeNode.create({
    data: {
      treeId: tree.id,
      parentId: concernPath.id,
      name: 'Expert Response Promise',
      nodeType: 'send_message',
      content: `Thank you for sharing that with me, {{name}}. 🤝

Your concerns are completely valid and important to us. Dr. [Specialist] will personally call you within the next 2 hours to address everything you've mentioned.

In the meantime, would you like me to send you some additional resources that might help? Just say "yes" or "no".`,
      sortOrder: 1
    }
  });

  // Different Time Path - Ultra Flexible
  const flexibleReschedule = await prisma.treeNode.create({
    data: {
      treeId: tree.id,
      parentId: immediateIntervention.id,
      name: 'Ultra-Flexible Rescheduling',
      nodeType: 'send_buttons',
      content: JSON.stringify({
        message: `Absolutely! Let's find the perfect time for you 📅

We have maximum flexibility for valued clients like you:`,
        buttons: [
          { id: 'this_week', text: '📆 Later This Week' },
          { id: 'next_week', text: '📅 Next Week' },
          { id: 'morning_person', text: '🌅 I\'m a Morning Person' },
          { id: 'evening_person', text: '🌆 Evening Works Better' }
        ]
      }),
      conditions: JSON.stringify({ keywords: ['different_time', 'reschedule'] }),
      sortOrder: 2
    }
  });

  // Medium Risk: Gentle Check-in
  const gentleCheckin = await prisma.treeNode.create({
    data: {
      treeId: tree.id,
      parentId: root.id,
      name: 'Gentle Check-in',
      nodeType: 'send_message',
      content: `Hi {{name}}! 😊 Hope you're having a great day!

Quick check-in about your {{treatment}} appointment. Everything still looking good for {{date}} at {{time}}?

Just reply "yes" if you're all set, or let me know if anything has changed! ✨`,
      conditions: JSON.stringify({ conditionResult: false }),
      sortOrder: 2
    }
  });

  console.log('✅ Smart No-Show Prevention Tree created');
}

// ═══════════════════════════════════════════════════════════════════
// 🎊 POST-TREATMENT DELIGHT JOURNEY
// ═══════════════════════════════════════════════════════════════════

async function createPostTreatmentDelightTree(clinicId: string): Promise<void> {
  console.log('🎊 Creating Post-Treatment Delight Journey...');

  const tree = await prisma.reminderTree.create({
    data: {
      clinicId,
      name: 'Post-Treatment Delight Journey',
      description: 'Transform satisfied clients into raving fans with surprise and delight',
      triggerType: 'completed',
      version: 1,
      metadata: JSON.stringify({
        tags: ['delight', 'retention', 'surprise'],
        targetOutcome: 'increased_ltv'
      })
    }
  });

  // Root: Immediate Thank You
  const root = await prisma.treeNode.create({
    data: {
      treeId: tree.id,
      name: 'Immediate Gratitude',
      nodeType: 'send_message',
      content: `Thank you for choosing {{clinic}}, {{name}}! 🌟

It was wonderful having you today for your {{treatment}}. You were absolutely lovely to work with!

How are you feeling? Take a moment to rest and let the results settle in. ✨`,
      offsetMinutes: 30, // 30 minutes after appointment
      sortOrder: 1
    }
  });

  // Wait 2 hours for aftercare
  const aftercareWait = await prisma.treeNode.create({
    data: {
      treeId: tree.id,
      parentId: root.id,
      name: 'Aftercare Window',
      nodeType: 'wait',
      offsetMinutes: 120, // 2 hours later
      sortOrder: 1
    }
  });

  // Personalized Aftercare
  const aftercareMessage = await prisma.treeNode.create({
    data: {
      treeId: tree.id,
      parentId: aftercareWait.id,
      name: 'Personalized Aftercare',
      nodeType: 'send_buttons',
      content: JSON.stringify({
        message: `Hi {{name}}! 💚 Hope you're feeling amazing after your {{treatment}}!

Here's your personalized aftercare plan:

{{aftercareInstructions}}

How would you like to track your progress?`,
        buttons: [
          { id: 'photo_journey', text: '📸 Photo Progress Journal' },
          { id: 'daily_checkins', text: '📝 Daily Check-ins' },
          { id: 'week_summary', text: '📊 Weekly Summary' },
          { id: 'no_tracking', text: '🙂 I\'m Good, Thanks!' }
        ]
      }),
      sortOrder: 1
    }
  });

  // Photo Journey Path
  const photoJourney = await prisma.treeNode.create({
    data: {
      treeId: tree.id,
      parentId: aftercareMessage.id,
      name: 'Photo Progress Setup',
      nodeType: 'send_message',
      content: `Perfect choice! 📸 Your photo progress journal will help track your amazing transformation.

🎯 PHOTO TIPS:
• Same lighting & angle each day
• Morning photos work best
• Keep it simple - you're beautiful!

I'll check in with you in 3 days to see your progress. Ready to document your journey? ✨`,
      conditions: JSON.stringify({ keywords: ['photo_journey'] }),
      sortOrder: 1
    }
  });

  // 3-Day Surprise Check-in
  const surpriseCheckin = await prisma.treeNode.create({
    data: {
      treeId: tree.id,
      parentId: photoJourney.id,
      name: 'Surprise Check-in',
      nodeType: 'send_buttons',
      content: JSON.stringify({
        message: `{{name}}, it's been 3 days! 🎉 How are you feeling about your {{treatment}} results?

I have a little surprise for you... 🎁`,
        buttons: [
          { id: 'feeling_great', text: '😍 Feeling Amazing!' },
          { id: 'good_results', text: '👍 Good Results' },
          { id: 'still_healing', text: '🔄 Still Healing' }
        ]
      }),
      offsetMinutes: 4320, // 3 days
      sortOrder: 1
    }
  });

  // Amazing Results - Reward Path
  const amazingResultsReward = await prisma.treeNode.create({
    data: {
      treeId: tree.id,
      parentId: surpriseCheckin.id,
      name: 'Amazing Results Reward',
      nodeType: 'send_message',
      content: `I KNEW IT! 😍✨ Your glow is probably incredible right now!

🎁 SURPRISE TIME! 🎁

As our gift to you for being such an amazing client, here's a special treat:

🎟️ 30% off your next treatment
🍃 Complimentary skincare consultation  
💆 Free 15-min add-on service

You deserve to feel this amazing all the time! Book within 7 days to claim your rewards.

Want me to hold a preferred time slot for you? ✨`,
      conditions: JSON.stringify({ keywords: ['feeling_great', 'amazing'] }),
      sortOrder: 1
    }
  });

  // Still Healing - Gentle Support
  const gentleSupport = await prisma.treeNode.create({
    data: {
      treeId: tree.id,
      parentId: surpriseCheckin.id,
      name: 'Healing Support',
      nodeType: 'send_message',
      content: `That's perfectly normal, {{name}}! 🤗 Healing is a beautiful process and everyone's timeline is different.

You're doing everything right. Trust the process - your results will be worth the wait! 

💜 Our specialist would love to check in with you personally. Would you like Dr. [Name] to give you a quick call tomorrow just to see how you're doing?

Just reply "yes" or "no" - no pressure! We're here for you either way. ✨`,
      conditions: JSON.stringify({ keywords: ['still_healing', 'healing'] }),
      sortOrder: 3
    }
  });

  // 7-Day Delight Bomb
  const delightBomb = await prisma.treeNode.create({
    data: {
      treeId: tree.id,
      parentId: amazingResultsReward.id,
      name: '7-Day Delight Bomb',
      nodeType: 'send_buttons',
      content: JSON.stringify({
        message: `{{name}}, can I share something exciting? 🌟

You've been selected as our CLIENT OF THE WEEK! 👑

This means:
🎊 Feature in our success stories (with permission)
🎁 Exclusive access to new treatments
💎 VIP priority booking forever
🌸 Surprise gift package being prepared

How does that sound?`,
        buttons: [
          { id: 'so_honored', text: '😭 I\'m So Honored!' },
          { id: 'tell_friends', text: '📢 I\'ll Tell My Friends!' },
          { id: 'private_please', text: '🤫 Keep It Private Please' }
        ]
      }),
      offsetMinutes: 10080, // 7 days
      sortOrder: 1
    }
  });

  console.log('✅ Post-Treatment Delight Journey created');
}

// ═══════════════════════════════════════════════════════════════════
// 🎪 REFERRAL MULTIPLICATION SYSTEM
// ═══════════════════════════════════════════════════════════════════

async function createReferralMultiplicationTree(clinicId: string): Promise<void> {
  console.log('🎪 Creating Referral Multiplication System...');

  const tree = await prisma.reminderTree.create({
    data: {
      clinicId,
      name: 'Referral Multiplication Engine',
      description: 'Turn every happy client into a referral generating machine',
      triggerType: 'custom',
      version: 1,
      metadata: JSON.stringify({
        tags: ['referral', 'multiplication', 'viral'],
        triggerConditions: ['high_satisfaction', 'completed_treatment']
      })
    }
  });

  // Root: Satisfaction Assessment
  const root = await prisma.treeNode.create({
    data: {
      treeId: tree.id,
      name: 'Satisfaction Scanner',
      nodeType: 'condition',
      conditions: JSON.stringify([
        {
          type: 'engagement_score',
          operator: 'gt',
          value: 80,
          weight: 0.5
        }
      ]),
      offsetMinutes: 7200, // 5 days after treatment
      sortOrder: 1
    }
  });

  // High Satisfaction: Referral Activation
  const referralActivation = await prisma.treeNode.create({
    data: {
      treeId: tree.id,
      parentId: root.id,
      name: 'Referral Activation Sequence',
      nodeType: 'send_message',
      content: `{{name}}, I have to ask... 😊

Are you as happy with your {{treatment}} results as I think you are? Because honestly, you've been GLOWING in all our interactions! ✨

I'm almost certain your friends have been asking about your secret... 😉`,
      conditions: JSON.stringify({ conditionResult: true }),
      sortOrder: 1
    }
  });

  // Wait for response
  const responseWait = await prisma.treeNode.create({
    data: {
      treeId: tree.id,
      parentId: referralActivation.id,
      name: 'Response Collection Window',
      nodeType: 'wait',
      offsetMinutes: 1440, // 24 hours
      sortOrder: 1
    }
  });

  // Referral Offer
  const referralOffer = await prisma.treeNode.create({
    data: {
      treeId: tree.id,
      parentId: responseWait.id,
      name: 'Irresistible Referral Offer',
      nodeType: 'send_buttons',
      content: JSON.stringify({
        message: `{{name}}, what if I told you that you could give your friends the SAME amazing experience you had... 

🎁 AND both of you get rewarded for it?

Here's our "Friends Don't Let Friends Look Basic" program:

💎 YOU GET: $50 credit for each friend who books
💎 YOUR FRIEND GETS: 25% off their first treatment
💎 EVERYONE GETS: VIP status for life

Sound good?`,
        buttons: [
          { id: 'count_me_in', text: '🙌 Count Me In!' },
          { id: 'tell_me_more', text: '🤔 Tell Me More' },
          { id: 'maybe_later', text: '⏰ Maybe Later' }
        ]
      }),
      sortOrder: 1
    }
  });

  // Count Me In Path
  const countMeIn = await prisma.treeNode.create({
    data: {
      treeId: tree.id,
      parentId: referralOffer.id,
      name: 'Referral Toolkit Delivery',
      nodeType: 'send_message',
      content: `YES! 🎉 I love your energy, {{name}}!

🎒 YOUR REFERRAL TOOLKIT:

📱 Personal referral link: clinic.com/{{name}}
💬 "Share this with friends" templates
📸 Before/after photo permission form
🎁 Referral tracking dashboard
💳 Digital wallet for your credits

BONUS: Refer 3 friends this month = Mystery luxury treatment FREE! 🌟

Your toolkit is being prepared and will arrive via email in 10 minutes. Ready to spread the glow? ✨`,
      conditions: JSON.stringify({ keywords: ['count_me_in'] }),
      sortOrder: 1
    }
  });

  // Follow-up Referral Coaching
  const referralCoaching = await prisma.treeNode.create({
    data: {
      treeId: tree.id,
      parentId: countMeIn.id,
      name: 'Referral Success Coaching',
      nodeType: 'send_buttons',
      content: JSON.stringify({
        message: `{{name}}, want to know the secret to getting the MOST referrals? 🤫

It's all about timing and approach. Let me coach you:

Which scenario sounds most like you?`,
        buttons: [
          { id: 'social_butterfly', text: '🦋 Social Butterfly' },
          { id: 'close_circle', text: '👥 Close Circle Only' },
          { id: 'natural_advisor', text: '💡 Natural Advisor' }
        ]
      }),
      offsetMinutes: 60, // 1 hour later
      sortOrder: 1
    }
  });

  console.log('✅ Referral Multiplication System created');
}

// ═══════════════════════════════════════════════════════════════════
// 🎬 MAIN EXECUTION
// ═══════════════════════════════════════════════════════════════════

export async function createAllDemoTrees(clinicId: string): Promise<void> {
  console.log('🚀 Creating ALL Demo Trees for Ultimate Patient Experience...\n');

  try {
    await createPremiumBookingTree(clinicId);
    console.log('');
    
    await createNoShowPreventionTree(clinicId);
    console.log('');
    
    await createPostTreatmentDelightTree(clinicId);
    console.log('');
    
    await createReferralMultiplicationTree(clinicId);
    console.log('');

    console.log('🎉 ALL DEMO TREES CREATED SUCCESSFULLY! 🎉');
    console.log('');
    console.log('🌟 Your clinic now has:');
    console.log('   ✅ Premium Booking Experience Tree');
    console.log('   ✅ AI No-Show Prevention System'); 
    console.log('   ✅ Post-Treatment Delight Journey');
    console.log('   ✅ Referral Multiplication Engine');
    console.log('');
    console.log('💡 These trees will automatically activate based on:');
    console.log('   • Patient behavior patterns');
    console.log('   • Engagement scores');
    console.log('   • Risk assessment algorithms');
    console.log('   • Satisfaction indicators');
    console.log('');
    console.log('🚀 Your patients are about to experience the future of healthcare communication!');

  } catch (error) {
    console.error('❌ Error creating demo trees:', error);
    throw error;
  } finally {
    await prisma.$disconnect();
  }
}

// Run if this file is executed directly
if (require.main === module) {
  const clinicId = process.argv[2];
  
  if (!clinicId) {
    console.error('❌ Please provide a clinic ID as argument');
    console.error('Usage: npm run demo-trees <clinic-id>');
    process.exit(1);
  }

  createAllDemoTrees(clinicId)
    .catch(console.error)
    .finally(() => process.exit(0));
}