require('dotenv').config();
const { createClient } = require('@supabase/supabase-js');

const supabase = createClient(
  process.env.SUPABASE_URL,
  process.env.SUPABASE_SERVICE_KEY
);

// AI Profile variety for natural responses
const OPENING_STYLES = [
  "Here's what I found:",
  "Based on my research:",
  "I've completed the task. Here are the results:",
  "Task completed. Here's my work:",
  "After thorough research, here's my response:",
];

async function fixAndProcessAllPending() {
  console.log('🔧 AI AGENTS COMPREHENSIVE FIX\n');
  
  // 1. Find all stuck in_progress submissions
  const { data: stuck, error } = await supabase
    .from('submissions')
    .select('id, task_id, worker_id, created_at')
    .eq('status', 'in_progress');
  
  if (error) {
    console.log('❌ Error fetching submissions:', error.message);
    return;
  }
  
  console.log(`📊 Found ${stuck?.length || 0} stuck in_progress submissions\n`);
  
  if (!stuck || stuck.length === 0) {
    console.log('✅ No stuck submissions to process!');
    return;
  }
  
  const apiKey = process.env.DEEPSEEK_API_KEY;
  if (!apiKey) {
    console.log('❌ DEEPSEEK_API_KEY not configured!');
    return;
  }
  
  let completed = 0;
  let failed = 0;
  
  for (const sub of stuck) {
    // Get task details
    const { data: task } = await supabase
      .from('tasks')
      .select('title, description, category, budget')
      .eq('id', sub.task_id)
      .single();
    
    if (!task) {
      console.log('⚠️ Task not found for submission:', sub.id);
      continue;
    }
    
    console.log(`🤖 Processing: ${task.title} (Ⓥ${task.budget})`);
    
    // Varied opening style
    const style = OPENING_STYLES[Math.floor(Math.random() * OPENING_STYLES.length)];
    
    const prompt = `You are a skilled freelancer completing a microtask on a gig platform.

TASK: ${task.title}
CATEGORY: ${task.category}
INSTRUCTIONS: ${task.description}

Complete this task professionally and thoroughly. Start your response directly with the content (no "Of course" or "Sure" - just deliver the work).

Provide genuine, helpful, detailed content that would satisfy the requester.`;

    try {
      const response = await fetch('https://api.deepseek.com/v1/chat/completions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${apiKey}`
        },
        body: JSON.stringify({
          model: 'deepseek-chat',
          messages: [{ role: 'user', content: prompt }],
          temperature: 0.7,
          max_tokens: 2000  // INCREASED from 1000
        })
      });

      const data = await response.json();
      
      if (data.error) {
        console.log(`   ❌ API error: ${data.error.message}`);
        failed++;
        continue;
      }
      
      const content = data.choices?.[0]?.message?.content;
      
      if (!content) {
        console.log('   ❌ Empty response from DeepSeek');
        failed++;
        continue;
      }
      
      // Update submission with ALL correct fields
      const { error: updateError } = await supabase
        .from('submissions')
        .update({
          content: content,
          status: 'submitted',
          submitted_at: new Date().toISOString(),
          is_ai: true,  // IMPORTANT: Mark as AI
          updated_at: new Date().toISOString()
        })
        .eq('id', sub.id);
      
      if (updateError) {
        console.log(`   ❌ DB error: ${updateError.message}`);
        failed++;
      } else {
        console.log(`   ✅ Completed (${content.length} chars)`);
        completed++;
      }
      
      // Rate limiting - 1 second between calls
      await new Promise(r => setTimeout(r, 1000));
      
    } catch (err) {
      console.log(`   ❌ Fetch error: ${err.message}`);
      failed++;
    }
  }
  
  console.log('\n' + '='.repeat(50));
  console.log(`✅ Completed: ${completed}`);
  console.log(`❌ Failed: ${failed}`);
  console.log('='.repeat(50));
}

fixAndProcessAllPending();
