/**
 * ═══════════════════════════════════════════════════════════════════════════════
 * LOOPUMAN AI AUTOMATION SERVICE
 * ═══════════════════════════════════════════════════════════════════════════════
 * 
 * AI-powered automation for scaling Loopuman without hiring staff.
 * 
 * FEATURES:
 * 1. AUTO TASK MODERATION - Approve/reject tasks instantly
 * 2. AUTO DISPUTE RESOLUTION - Handle 80%+ of disputes without human
 * 3. FRAUD DETECTION - Flag suspicious accounts/activity
 * 4. QUALITY SCORING - Auto-score submission quality
 * 5. SMART MATCHING - Match workers to tasks they're best suited for
 * 
 * COST: Uses DeepSeek API (~$0.001 per moderation)
 * 
 * SOLOPRENEUR SCALING:
 * - 1,000 tasks/day → ~$1/day in AI costs
 * - 10,000 tasks/day → ~$10/day in AI costs
 * - No staff needed until $1M+ revenue
 * 
 * ═══════════════════════════════════════════════════════════════════════════════
 */

'use strict';

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

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

// DeepSeek API configuration (cheapest high-quality LLM)
const DEEPSEEK_API_KEY = process.env.DEEPSEEK_API_KEY;
const DEEPSEEK_URL = 'https://api.deepseek.com/v1/chat/completions';

// ═══════════════════════════════════════════════════════════════════════════════
// AI HELPER - Call DeepSeek
// ═══════════════════════════════════════════════════════════════════════════════

async function callAI(systemPrompt, userMessage, options = {}) {
  try {
    const response = await fetch(DEEPSEEK_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${DEEPSEEK_API_KEY}`
      },
      body: JSON.stringify({
        model: options.model || 'deepseek-chat',
        messages: [
          { role: 'system', content: systemPrompt },
          { role: 'user', content: userMessage }
        ],
        temperature: options.temperature || 0.3,
        max_tokens: options.maxTokens || 500
      })
    });

    const data = await response.json();
    return {
      success: true,
      content: data.choices[0].message.content,
      usage: data.usage
    };
  } catch (error) {
    console.error('❌ AI call failed:', error.message);
    return { success: false, error: error.message };
  }
}

// ═══════════════════════════════════════════════════════════════════════════════
// 1. AUTO TASK MODERATION
// ═══════════════════════════════════════════════════════════════════════════════

const MODERATION_PROMPT = `You are a content moderator for Loopuman, a microtasking platform.

APPROVE tasks that are:
- Legal and ethical
- Clear instructions
- Fair compensation (not exploitative)
- Achievable by workers

REJECT tasks that:
- Request illegal activity
- Are scams or fraud
- Contain hate speech, violence, or adult content
- Ask for personal information harvesting
- Are impossible or misleading
- Pay less than $0.01 for >5 minutes work

Respond with JSON only:
{
  "decision": "approve" or "reject",
  "reason": "brief explanation",
  "flags": ["list", "of", "concerns"],
  "confidence": 0.0 to 1.0
}`;

async function moderateTask(task) {
  const taskDescription = `
TASK TITLE: ${task.title}
DESCRIPTION: ${task.description}
CATEGORY: ${task.category}
PAYMENT: ${task.budget_vae} VAE ($${(task.budget_vae / 100).toFixed(2)})
TIME ESTIMATE: ${task.estimated_time_minutes} minutes
REQUIREMENTS: ${task.requirements || 'None specified'}
`;

  const result = await callAI(MODERATION_PROMPT, taskDescription);
  
  if (!result.success) {
    return { approved: true, autoModerated: false, error: result.error };
  }

  try {
    const decision = JSON.parse(result.content);
    
    // Log moderation
    await supabase.from('moderation_logs').insert({
      task_id: task.id,
      action: decision.decision,
      reason: decision.reason,
      flags: decision.flags,
      confidence: decision.confidence,
      ai_model: 'deepseek-chat'
    });

    // Auto-approve if high confidence
    if (decision.decision === 'approve' && decision.confidence >= 0.85) {
      await supabase.from('tasks').update({ status: 'active', moderated_at: new Date().toISOString() }).eq('id', task.id);
      return { approved: true, autoModerated: true, decision };
    }

    // Auto-reject if high confidence
    if (decision.decision === 'reject' && decision.confidence >= 0.9) {
      await supabase.from('tasks').update({ status: 'rejected', rejection_reason: decision.reason }).eq('id', task.id);
      return { approved: false, autoModerated: true, decision };
    }

    // Flag for manual review if uncertain
    return { approved: null, autoModerated: false, needsReview: true, decision };

  } catch (e) {
    return { approved: true, autoModerated: false, parseError: true };
  }
}

// ═══════════════════════════════════════════════════════════════════════════════
// 2. AUTO DISPUTE RESOLUTION
// ═══════════════════════════════════════════════════════════════════════════════

const DISPUTE_PROMPT = `You are a fair dispute resolver for Loopuman microtasking platform.

Your job is to resolve disputes between requesters and workers fairly.

PRINCIPLES:
1. Evidence matters - who has proof?
2. Task instructions - were they clear?
3. Submission quality - did worker make genuine effort?
4. Communication - did parties try to resolve?
5. History - any pattern of bad behavior?

RESOLUTIONS:
- "worker_wins" - Worker did the job, pay them
- "requester_wins" - Work was genuinely substandard, refund
- "split" - Both have valid points, split payment 50/50
- "escalate" - Too complex, needs human review

Respond with JSON:
{
  "resolution": "worker_wins" | "requester_wins" | "split" | "escalate",
  "reason": "explanation for both parties",
  "worker_payment_percent": 0-100,
  "confidence": 0.0 to 1.0,
  "message_to_worker": "what to tell worker",
  "message_to_requester": "what to tell requester"
}`;

async function resolveDispute(dispute) {
  // Gather context
  const { data: task } = await supabase.from('tasks').select('*').eq('id', dispute.task_id).single();
  const { data: submission } = await supabase.from('submissions').select('*').eq('id', dispute.submission_id).single();
  const { data: worker } = await supabase.from('app_users').select('tasks_completed, success_rate, average_rating').eq('id', dispute.worker_id).single();
  const { data: requester } = await supabase.from('app_users').select('tasks_posted, dispute_rate').eq('id', dispute.requester_id).single();

  const context = `
DISPUTE ID: ${dispute.id}

TASK DETAILS:
- Title: ${task.title}
- Instructions: ${task.description}
- Payment: ${task.budget_vae} VAE
- Requirements: ${task.requirements}

SUBMISSION:
- Content: ${submission.content?.substring(0, 1000)}
- Submitted: ${submission.created_at}

REQUESTER COMPLAINT:
${dispute.requester_reason}

WORKER RESPONSE:
${dispute.worker_response || 'No response yet'}

WORKER HISTORY:
- Tasks completed: ${worker?.tasks_completed || 0}
- Success rate: ${worker?.success_rate || 100}%
- Average rating: ${worker?.average_rating || 5}/5

REQUESTER HISTORY:
- Tasks posted: ${requester?.tasks_posted || 0}
- Dispute rate: ${requester?.dispute_rate || 0}%
`;

  const result = await callAI(DISPUTE_PROMPT, context);
  
  if (!result.success) {
    return { resolved: false, error: result.error };
  }

  try {
    const decision = JSON.parse(result.content);
    
    // Only auto-resolve if high confidence
    if (decision.confidence >= 0.85 && decision.resolution !== 'escalate') {
      // Calculate payments
      const workerPayment = Math.round(task.budget_vae * (decision.worker_payment_percent / 100));
      const refund = task.budget_vae - workerPayment;
      
      // Update dispute
      await supabase.from('disputes').update({
        status: 'resolved',
        resolution: decision.resolution,
        reason: decision.reason,
        worker_payment: workerPayment,
        requester_refund: refund,
        resolved_by: 'ai',
        resolved_at: new Date().toISOString()
      }).eq('id', dispute.id);

      // Process payments
      if (workerPayment > 0) {
        await creditWorker(dispute.worker_id, workerPayment);
      }
      if (refund > 0) {
        await creditRequester(dispute.requester_id, refund);
      }

      return {
        resolved: true,
        autoResolved: true,
        decision,
        workerPayment,
        refund
      };
    }

    // Escalate to human
    await supabase.from('disputes').update({
      status: 'escalated',
      ai_recommendation: decision,
      escalated_at: new Date().toISOString()
    }).eq('id', dispute.id);

    return { resolved: false, escalated: true, recommendation: decision };

  } catch (e) {
    return { resolved: false, parseError: true };
  }
}

async function creditWorker(userId, amount) {
  const { data } = await supabase.from('vae_balances').select('earnings_balance').eq('user_id', userId).single();
  await supabase.from('vae_balances').update({ earnings_balance: (data?.earnings_balance || 0) + amount }).eq('user_id', userId);
}

async function creditRequester(userId, amount) {
  const { data } = await supabase.from('vae_balances').select('deposit_balance').eq('user_id', userId).single();
  await supabase.from('vae_balances').update({ deposit_balance: (data?.deposit_balance || 0) + amount }).eq('user_id', userId);
}

// ═══════════════════════════════════════════════════════════════════════════════
// 3. FRAUD DETECTION
// ═══════════════════════════════════════════════════════════════════════════════

const FRAUD_SIGNALS = {
  // Account signals
  new_account_high_volume: { weight: 0.3, description: 'New account with unusually high activity' },
  multiple_accounts_same_device: { weight: 0.5, description: 'Multiple accounts from same device' },
  withdrawal_immediately: { weight: 0.2, description: 'Withdrawal request immediately after earning' },
  
  // Behavior signals
  always_same_requester: { weight: 0.4, description: 'Worker only completes tasks from same requester' },
  impossibly_fast: { weight: 0.5, description: 'Completing tasks faster than humanly possible' },
  copy_paste_submissions: { weight: 0.4, description: 'Identical submissions across tasks' },
  
  // Pattern signals
  burst_activity: { weight: 0.3, description: 'Sudden burst of activity after dormancy' },
  geographic_mismatch: { weight: 0.2, description: 'Activity from unusual location' }
};

async function detectFraud(userId) {
  const signals = [];
  let riskScore = 0;

  // Get user data
  const { data: user } = await supabase.from('app_users').select('*').eq('id', userId).single();
  const { data: submissions } = await supabase.from('submissions').select('*').eq('worker_id', userId).order('created_at', { ascending: false }).limit(50);
  const { data: withdrawals } = await supabase.from('withdrawals').select('*').eq('user_id', userId).limit(10);

  // Check: New account high volume
  const accountAgeDays = (Date.now() - new Date(user.created_at).getTime()) / (1000 * 60 * 60 * 24);
  if (accountAgeDays < 7 && (user.tasks_completed || 0) > 50) {
    signals.push(FRAUD_SIGNALS.new_account_high_volume);
    riskScore += FRAUD_SIGNALS.new_account_high_volume.weight;
  }

  // Check: Impossibly fast completions
  if (submissions?.length > 0) {
    const fastSubmissions = submissions.filter(s => {
      const timeMinutes = s.time_spent_seconds ? s.time_spent_seconds / 60 : 0;
      const expectedMinutes = s.estimated_time_minutes || 5;
      return timeMinutes < expectedMinutes * 0.2; // Less than 20% of expected time
    });
    if (fastSubmissions.length > submissions.length * 0.3) {
      signals.push(FRAUD_SIGNALS.impossibly_fast);
      riskScore += FRAUD_SIGNALS.impossibly_fast.weight;
    }
  }

  // Check: Immediate withdrawal
  if (withdrawals?.length > 0 && accountAgeDays < 3) {
    signals.push(FRAUD_SIGNALS.withdrawal_immediately);
    riskScore += FRAUD_SIGNALS.withdrawal_immediately.weight;
  }

  // Check: Same requester
  if (submissions?.length >= 10) {
    const requesters = [...new Set(submissions.map(s => s.requester_id))];
    if (requesters.length === 1) {
      signals.push(FRAUD_SIGNALS.always_same_requester);
      riskScore += FRAUD_SIGNALS.always_same_requester.weight;
    }
  }

  // Determine risk level
  let riskLevel = 'low';
  if (riskScore >= 0.7) riskLevel = 'high';
  else if (riskScore >= 0.4) riskLevel = 'medium';

  // Log if medium+ risk
  if (riskLevel !== 'low') {
    await supabase.from('fraud_alerts').insert({
      user_id: userId,
      risk_score: riskScore,
      risk_level: riskLevel,
      signals: signals,
      status: 'pending_review'
    });
  }

  // Auto-flag high risk
  if (riskLevel === 'high') {
    await supabase.from('app_users').update({ 
      flagged: true, 
      flag_reason: 'Automated fraud detection',
      flag_signals: signals 
    }).eq('id', userId);
  }

  return { riskScore, riskLevel, signals };
}

// ═══════════════════════════════════════════════════════════════════════════════
// 4. QUALITY SCORING
// ═══════════════════════════════════════════════════════════════════════════════

const QUALITY_PROMPT = `You are a quality evaluator for microtask submissions.

Score the submission from 1-5:
5 = Excellent - Exceeds requirements
4 = Good - Meets all requirements
3 = Acceptable - Meets minimum requirements
2 = Poor - Missing some requirements
1 = Unacceptable - Does not meet requirements

Respond with JSON:
{
  "score": 1-5,
  "feedback": "brief feedback",
  "issues": ["list", "of", "issues"],
  "meets_requirements": true/false
}`;

async function scoreSubmission(submission, task) {
  const context = `
TASK:
- Title: ${task.title}
- Instructions: ${task.description}
- Requirements: ${task.requirements || 'None specified'}

SUBMISSION:
${submission.content?.substring(0, 2000)}
`;

  const result = await callAI(QUALITY_PROMPT, context, { temperature: 0.2 });
  
  if (!result.success) {
    return { score: null, error: result.error };
  }

  try {
    const quality = JSON.parse(result.content);
    
    // Update submission
    await supabase.from('submissions').update({
      quality_score: quality.score,
      quality_feedback: quality.feedback,
      quality_issues: quality.issues,
      auto_scored: true
    }).eq('id', submission.id);

    // Auto-approve if score >= 4
    if (quality.score >= 4 && quality.meets_requirements) {
      return { score: quality.score, autoApprove: true, quality };
    }

    // Auto-reject if score <= 2
    if (quality.score <= 2 && !quality.meets_requirements) {
      return { score: quality.score, autoReject: true, quality };
    }

    return { score: quality.score, needsReview: true, quality };

  } catch (e) {
    return { score: null, parseError: true };
  }
}

// ═══════════════════════════════════════════════════════════════════════════════
// 5. SMART WORKER MATCHING
// ═══════════════════════════════════════════════════════════════════════════════

async function findBestWorkers(task, limit = 10) {
  // Get workers with relevant skills
  const { data: workers } = await supabase
    .from('app_users')
    .select('*')
    .eq('role', 'worker')
    .eq('status', 'active')
    .gte('success_rate', 80)
    .order('average_rating', { ascending: false })
    .limit(50);

  if (!workers) return [];

  // Score each worker for this task
  const scored = workers.map(worker => {
    let score = 0;
    
    // Rating weight
    score += (worker.average_rating || 3) * 10;
    
    // Success rate weight
    score += (worker.success_rate || 50) * 0.5;
    
    // Experience weight
    const taskCount = worker.tasks_completed || 0;
    if (taskCount >= 100) score += 20;
    else if (taskCount >= 50) score += 15;
    else if (taskCount >= 10) score += 10;
    
    // Category match (if tracked)
    if (worker.preferred_categories?.includes(task.category)) {
      score += 25;
    }
    
    // Recent activity bonus
    const lastActive = new Date(worker.last_active_at || worker.created_at);
    const daysSinceActive = (Date.now() - lastActive.getTime()) / (1000 * 60 * 60 * 24);
    if (daysSinceActive < 1) score += 15;
    else if (daysSinceActive < 7) score += 10;
    
    return { ...worker, matchScore: score };
  });

  // Sort by score and return top matches
  return scored
    .sort((a, b) => b.matchScore - a.matchScore)
    .slice(0, limit);
}

// ═══════════════════════════════════════════════════════════════════════════════
// DAILY AUTOMATION SUMMARY (for Ray)
// ═══════════════════════════════════════════════════════════════════════════════

async function getDailyAutomationStats() {
  const today = new Date();
  today.setHours(0, 0, 0, 0);

  const { data: moderations } = await supabase
    .from('moderation_logs')
    .select('action')
    .gte('created_at', today.toISOString());

  const { data: disputes } = await supabase
    .from('disputes')
    .select('resolved_by')
    .gte('resolved_at', today.toISOString());

  const { data: fraudAlerts } = await supabase
    .from('fraud_alerts')
    .select('risk_level')
    .gte('created_at', today.toISOString());

  const autoApproved = moderations?.filter(m => m.action === 'approve').length || 0;
  const autoRejected = moderations?.filter(m => m.action === 'reject').length || 0;
  const aiResolved = disputes?.filter(d => d.resolved_by === 'ai').length || 0;
  const humanResolved = disputes?.filter(d => d.resolved_by === 'human').length || 0;
  const fraudCaught = fraudAlerts?.filter(f => f.risk_level === 'high').length || 0;

  return {
    date: today.toISOString().split('T')[0],
    tasks_moderated: autoApproved + autoRejected,
    tasks_auto_approved: autoApproved,
    tasks_auto_rejected: autoRejected,
    disputes_ai_resolved: aiResolved,
    disputes_human_resolved: humanResolved,
    automation_rate: aiResolved + humanResolved > 0 
      ? Math.round((aiResolved / (aiResolved + humanResolved)) * 100) 
      : 0,
    fraud_alerts: fraudCaught,
    estimated_time_saved_hours: Math.round((autoApproved + autoRejected + aiResolved) * 2 / 60) // 2 min per manual action
  };
}

// ═══════════════════════════════════════════════════════════════════════════════
// EXPORTS
// ═══════════════════════════════════════════════════════════════════════════════

module.exports = {
  // Task moderation
  moderateTask,
  
  // Dispute resolution
  resolveDispute,
  
  // Fraud detection
  detectFraud,
  
  // Quality scoring
  scoreSubmission,
  
  // Smart matching
  findBestWorkers,
  
  // Stats
  getDailyAutomationStats,
  
  // Raw AI access
  callAI
};
