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

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

async function testDeepSeekSubmission() {
  // Get one in_progress submission
  const { data: submission, error } = await supabase
    .from('submissions')
    .select('id, task_id, worker_id')
    .eq('status', 'in_progress')
    .limit(1)
    .single();
  
  if (error || !submission) {
    console.log('No in_progress submission found');
    return;
  }
  
  // Get task details
  const { data: task } = await supabase
    .from('tasks')
    .select('title, description')
    .eq('id', submission.task_id)
    .single();
  
  console.log('📝 Testing DeepSeek on task:', task.title);
  console.log('Description:', task.description);
  console.log('\n🤖 Calling DeepSeek API...\n');
  
  const apiKey = process.env.DEEPSEEK_API_KEY;
  if (!apiKey) {
    console.log('❌ DEEPSEEK_API_KEY not set!');
    return;
  }
  
  const prompt = `You are a skilled freelancer completing a microtask.

TASK: ${task.title}

INSTRUCTIONS: ${task.description}

Complete this task professionally. Provide a genuine, helpful response.`;

  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: 1000
      })
    });

    const data = await response.json();
    
    if (data.error) {
      console.log('❌ DeepSeek API error:', data.error.message);
      return;
    }
    
    const content = data.choices[0].message.content;
    console.log('✅ DeepSeek Response:\n');
    console.log(content);
    console.log('\n--- Response length:', content.length, 'chars ---\n');
    
    // Update submission with content
    const { error: updateError } = await supabase
      .from('submissions')
      .update({
        content: content,
        status: 'submitted',
        submitted_at: new Date().toISOString(),
        is_ai: true
      })
      .eq('id', submission.id);
    
    if (updateError) {
      console.log('❌ Failed to update submission:', updateError.message);
    } else {
      console.log('✅ Submission updated successfully!');
      console.log('Task completed:', task.title);
    }
    
  } catch (err) {
    console.log('❌ Fetch error:', err.message);
  }
}

testDeepSeekSubmission();
