#!/bin/bash

# LOOPUMAN COMPLETE LAUNCH SCRIPT
# This sets up everything for testing

echo "🚀 LOOPUMAN COMPLETE SETUP"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

# Load environment
if [ ! -f .env ]; then
  echo "❌ .env file not found!"
  echo "📝 Copy .env.example to .env and configure it first"
  exit 1
fi

source .env

# Check required variables
if [ -z "$SUPABASE_URL" ] || [ -z "$YOUR_TELEGRAM_ID" ]; then
  echo "❌ Missing required environment variables"
  echo "Required: SUPABASE_URL, SUPABASE_SERVICE_KEY, YOUR_TELEGRAM_ID"
  exit 1
fi

echo "1️⃣  Adding Test Credits..."
node << 'EOF'
const { createClient } = require('@supabase/supabase-js');
const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_SERVICE_KEY);

async function setup() {
  const telegramId = process.env.YOUR_TELEGRAM_ID;
  
  // Find your user
  let { data: user } = await supabase
    .from('app_users')
    .select('id')
    .eq('telegram_id', telegramId)
    .single();
  
  if (!user) {
    console.log('❌ User not found. Start the Telegram bot first: /start');
    process.exit(1);
  }
  
  const userId = user.id;
  console.log('✅ Found user:', userId.slice(0, 8) + '...');
  
  // Add credits
  await supabase
    .from('vae_balances')
    .upsert({
      user_id: userId,
      deposit_balance: 100000,  // Ⓥ100,000 = $1,000 for posting tasks
      earned_balance: 5000      // Ⓥ5,000 = $50 for testing withdrawals
    }, { onConflict: 'user_id' });
  
  console.log('✅ Added credits:');
  console.log('   Requester: Ⓥ100,000 ($1,000)');
  console.log('   Worker: Ⓥ5,000 ($50)');
  console.log('');
  
  process.exit(0);
}

setup().catch(err => {
  console.error('❌ Error:', err.message);
  process.exit(1);
});
EOF

if [ $? -ne 0 ]; then
  echo "❌ Failed to add credits"
  exit 1
fi

echo ""
echo "2️⃣  Creating 20 Test Tasks..."
node << 'EOF'
const { createClient } = require('@supabase/supabase-js');
const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_SERVICE_KEY);

const TEST_TASKS = [
  // AI-eligible tasks (remote, writing/research/data)
  { title: 'Write 3 product descriptions for wireless earbuds', category: 'writing', budget: 100, workers: 1, type: 'remote' },
  { title: 'Research top 5 fitness trends in 2026', category: 'research', budget: 150, workers: 2, type: 'remote' },
  { title: 'Categorize 20 images as indoor/outdoor', category: 'data_entry', budget: 80, workers: 1, type: 'remote' },
  { title: 'Write 5 Instagram captions for coffee shop', category: 'creative', budget: 120, workers: 1, type: 'remote' },
  { title: 'Summarize this 2000-word article', category: 'research', budget: 100, workers: 2, type: 'remote' },
  { title: 'Write 10 FAQs for SaaS product', category: 'writing', budget: 200, workers: 1, type: 'remote' },
  { title: 'Find contact emails for 10 restaurants', category: 'research', budget: 150, workers: 1, type: 'remote' },
  { title: 'Tag 50 products with correct categories', category: 'data_entry', budget: 100, workers: 2, type: 'remote' },
  { title: 'Write blog post about remote work (500 words)', category: 'writing', budget: 250, workers: 1, type: 'remote' },
  { title: 'Create 10 quiz questions about history', category: 'creative', budget: 120, workers: 1, type: 'remote' },
  
  // Human-only tasks (AI training, local, photos)
  { title: 'Rate AI assistant responses (10 conversations)', category: 'ai_training', budget: 200, workers: 3, type: 'remote' },
  { title: 'Take photo of billboard at Oxford Street', category: 'photos', budget: 300, workers: 1, type: 'local' },
  { title: 'Visit Tesco and check milk prices', category: 'other', budget: 200, workers: 2, type: 'local' },
  { title: 'Verify restaurant opening hours in person', category: 'other', budget: 150, workers: 1, type: 'local' },
  { title: 'Label which AI responses are more helpful (20 pairs)', category: 'ai_training', budget: 400, workers: 5, type: 'remote' },
  
  // Competition tasks (multiple workers)
  { title: 'Best logo design for tech startup', category: 'creative', budget: 500, workers: 5, type: 'remote' },
  { title: 'Most creative name for meal planning app', category: 'creative', budget: 200, workers: 10, type: 'remote' },
  { title: 'Best marketing slogan (10 words max)', category: 'writing', budget: 300, workers: 8, type: 'remote' },
  { title: 'Research and rank top 10 productivity apps', category: 'research', budget: 250, workers: 3, type: 'remote' },
  { title: 'Write the most engaging tweet about AI', category: 'writing', budget: 150, workers: 6, type: 'remote' }
];

async function createTasks() {
  const telegramId = process.env.YOUR_TELEGRAM_ID;
  
  let { data: user } = await supabase
    .from('app_users')
    .select('id')
    .eq('telegram_id', telegramId)
    .single();
  
  if (!user) {
    console.log('❌ User not found');
    process.exit(1);
  }
  
  const deadline = new Date();
  deadline.setDate(deadline.getDate() + 7); // 7 days from now
  
  let created = 0;
  
  for (const task of TEST_TASKS) {
    const { error } = await supabase.from('tasks').insert({
      requester_id: user.id,
      title: task.title,
      description: `Test task: ${task.title}\n\nThis is a test task for Loopuman launch. Complete professionally.`,
      category: task.category,
      task_type: task.type,
      budget_vae: task.budget,
      max_workers: task.workers,
      spots_filled: 0,
      status: 'open',
      deadline: deadline.toISOString(),
      required_tier: 0
    });
    
    if (!error) {
      created++;
      console.log(`✅ ${created}/20: ${task.title.slice(0, 50)}...`);
    }
  }
  
  console.log('');
  console.log(`✅ Created ${created} test tasks`);
  console.log('');
  console.log('Task breakdown:');
  console.log('  • 10 AI-eligible (remote writing/research/data)');
  console.log('  • 5 Human-only (ai_training, local, photos)');
  console.log('  • 5 Competition (multiple workers)');
  console.log('');
  
  process.exit(0);
}

createTasks().catch(err => {
  console.error('❌ Error:', err.message);
  process.exit(1);
});
EOF

if [ $? -ne 0 ]; then
  echo "❌ Failed to create test tasks"
  exit 1
fi

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "✅ SETUP COMPLETE!"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "📝 What's ready:"
echo "   ✅ Test credits added (Ⓥ100,000 requester + Ⓥ5,000 worker)"
echo "   ✅ 20 test tasks created"
echo "   ✅ Mix of AI-eligible and human-only tasks"
echo ""
echo "🧪 Now test:"
echo "   1. Telegram: Browse tasks and accept one"
echo "   2. Complete a task"
echo "   3. Request withdrawal (Ⓥ100 = \$1)"
echo "   4. Wait for AI agents to accept tasks (after 1-3 hours)"
echo "   5. WhatsApp: Review submissions"
echo ""
echo "📊 Monitor:"
echo "   pm2 logs ai-agents    # Watch AI agents work"
echo "   pm2 logs telegram-bot  # Watch bot activity"
echo ""
