require('dotenv').config();
const { createClient } = require('@supabase/supabase-js');
const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_SERVICE_KEY);

// Get the test requester (Agentic888)
async function getTestRequester() {
  const { data } = await supabase
    .from('app_users')
    .select('id')
    .eq('username', 'Agentic888')
    .single();
  return data?.id;
}

const tasks = [
  // Writing & Content
  { category: 'writing', title: 'Write 5 product descriptions for eco-friendly water bottles', description: 'Write compelling 100-150 word product descriptions for 5 different eco-friendly water bottles. Include features, benefits, and a call to action. Tone should be friendly and environmentally conscious.', budget: 300 },
  { category: 'writing', title: 'Create 10 engaging Instagram captions for a coffee brand', description: 'Write 10 creative Instagram captions for a specialty coffee brand. Each caption should be 50-100 words, include relevant hashtags, and encourage engagement. Mix promotional and lifestyle content.', budget: 200 },
  { category: 'writing', title: 'Write a 500-word blog post about remote work productivity tips', description: 'Create an informative blog post with practical tips for staying productive while working from home. Include an intro, 5-7 tips with explanations, and a conclusion. SEO-friendly with headers.', budget: 400 },
  
  // Research
  { category: 'research', title: 'Find 20 competitors for a meal kit delivery startup', description: 'Research and compile a list of 20 meal kit delivery services worldwide. Include company name, website, pricing range, unique selling points, and target market. Present in a structured format.', budget: 350 },
  { category: 'research', title: 'Research pricing strategies for SaaS products in fintech', description: 'Analyze pricing models of 10 fintech SaaS companies. Document their pricing tiers, features per tier, and any free trial offerings. Identify common patterns and unique approaches.', budget: 450 },
  { category: 'research', title: 'Find 15 TikTok influencers in the fitness niche (50k-200k followers)', description: 'Identify 15 fitness influencers on TikTok with 50k-200k followers. Include their username, follower count, engagement rate estimate, content style, and contact info if available.', budget: 250 },

  // Verification
  { category: 'verification', title: 'Verify contact information for 50 UK restaurants', description: 'Call or check websites for 50 UK restaurants to verify their phone number, email, and opening hours are correct. Mark any that have closed or changed details. Spreadsheet provided.', budget: 400 },
  { category: 'verification', title: 'Check if 30 mobile apps are still available on App Store', description: 'Verify whether 30 mobile apps are still available on the iOS App Store. Note the current version, last update date, and any name changes. List will be provided.', budget: 150 },
  { category: 'verification', title: 'Verify LinkedIn profiles of 25 job candidates', description: 'Cross-reference 25 job candidate resumes with their LinkedIn profiles. Check for consistency in job titles, dates, and company names. Note any discrepancies.', budget: 300 },

  // Surveys & Feedback
  { category: 'survey', title: 'Complete a 10-minute survey about online shopping habits', description: 'Take a detailed survey about your online shopping preferences, frequency, and favorite platforms. Answer honestly based on your real experiences. Survey link will be provided after acceptance.', budget: 50 },
  { category: 'survey', title: 'Provide feedback on a new mobile banking app prototype', description: 'Review screenshots and a demo video of a new mobile banking app. Answer 15 questions about the design, usability, and features. Share what you like and what could be improved.', budget: 100 },
  { category: 'survey', title: 'Rate and review 5 AI chatbot conversations', description: 'Have 5 short conversations with an AI chatbot and rate each response for helpfulness, accuracy, and naturalness. Provide written feedback on how each could be improved.', budget: 150 },

  // Translation
  { category: 'translation', title: 'Translate product listing from English to Spanish (500 words)', description: 'Translate an e-commerce product listing from English to Spanish. Maintain marketing tone and adapt cultural references appropriately. Native Spanish speakers preferred.', budget: 200 },
  { category: 'translation', title: 'Translate customer support FAQ from English to French (800 words)', description: 'Translate a customer support FAQ page from English to French. Ensure technical terms are correctly translated and the helpful tone is maintained.', budget: 280 },
  { category: 'translation', title: 'Translate app UI strings from English to Portuguese (100 strings)', description: 'Translate 100 short UI strings for a mobile app from English to Brazilian Portuguese. Keep translations concise to fit UI constraints. Context will be provided.', budget: 250 },

  // Transcription
  { category: 'transcription', title: 'Transcribe a 15-minute podcast interview', description: 'Transcribe a 15-minute podcast interview between two speakers. Include timestamps every 2 minutes. Clean verbatim (remove filler words). Audio is clear quality.', budget: 200 },
  { category: 'transcription', title: 'Transcribe 5 short customer service calls (2-3 min each)', description: 'Transcribe 5 recorded customer service calls. Label each speaker (Agent/Customer). Note any inaudible sections. Total audio: approximately 12 minutes.', budget: 180 },
  { category: 'transcription', title: 'Transcribe handwritten meeting notes to digital text', description: 'Convert 10 pages of handwritten meeting notes into typed text. Maintain the original structure and formatting as much as possible. Images of notes provided.', budget: 150 },

  // Micro Jobs
  { category: 'micro', title: 'Sign up for 3 newsletter and confirm email subscription', description: 'Sign up for 3 specified newsletters using your real email. Confirm the subscription by clicking the verification link. Take screenshots of confirmation. List provided.', budget: 30 },
  { category: 'micro', title: 'Download and rate 2 free apps on Play Store', description: 'Download 2 specified free apps from Google Play Store. Use each for 5 minutes, then leave an honest rating and short review. Screenshots required.', budget: 50 },
  { category: 'micro', title: 'Find and report 5 broken links on a website', description: 'Browse through a specified website and find 5 pages with broken links (404 errors). Document the page URL and the broken link for each. Website will be provided.', budget: 40 },

  // Local Tasks
  { category: 'local', title: 'Take 10 photos of menu boards at local coffee shops', description: 'Visit 3-5 coffee shops in your area and photograph their menu boards clearly. We need readable prices and items. Submit photos with location tags. GPS verification required.', budget: 300, is_local: true, location: 'Any city' },
  { category: 'local', title: 'Check product availability at 3 supermarkets', description: 'Visit 3 supermarkets and check if specific products are in stock. Note the price, shelf location, and take a photo of each. Product list provided. GPS required.', budget: 400, is_local: true, location: 'Any city' },
  { category: 'local', title: 'Collect business cards from 10 local restaurants', description: 'Visit local restaurants and collect their business cards or photograph their contact information displays. Need name, phone, address, and website if shown.', budget: 350, is_local: true, location: 'Any city' },

  // Mystery Shopping
  { category: 'mystery', title: 'Mystery shop a mobile phone store experience', description: 'Visit a mobile phone store, ask about upgrading your phone, and evaluate the sales experience. Rate staff knowledge, wait time, and store cleanliness. Detailed report required.', budget: 500, is_local: true, location: 'Any city' },
  { category: 'mystery', title: 'Evaluate customer service at a fast food restaurant', description: 'Order food at a specified fast food chain and evaluate: order accuracy, wait time, staff friendliness, and food quality. Keep receipt. Submit photos and detailed feedback.', budget: 400, is_local: true, location: 'Any city' },

  // Other
  { category: 'other', title: 'Create 5 sample customer personas for an e-commerce site', description: 'Develop 5 detailed customer personas for an online fashion retailer. Include demographics, shopping habits, pain points, and preferred social media platforms for each persona.', budget: 350 },
  { category: 'other', title: 'Organize and rename 100 product images', description: 'Rename and organize 100 product images according to a provided naming convention. Sort into category folders. Files will be shared via Google Drive.', budget: 150 },
  { category: 'other', title: 'Test a website checkout flow and report any bugs', description: 'Go through the complete checkout process on a test e-commerce site 5 times with different scenarios. Document any errors, UX issues, or bugs found. Screenshots required.', budget: 200 },

  // Enterprise AI Tasks
  { category: 'labeling', title: 'Label 200 images for object detection (vehicles)', description: 'Draw bounding boxes around vehicles in 200 street scene images. Label each as car, truck, motorcycle, bicycle, or bus. Labeling tool access provided.', budget: 400 },
  { category: 'labeling', title: 'Categorize 500 customer support tickets', description: 'Read and categorize 500 customer support tickets into predefined categories: billing, technical, account, shipping, returns, other. Training examples provided.', budget: 500 },
  
  { category: 'ai_training', title: 'Rate AI-generated responses for helpfulness (100 pairs)', description: 'Compare pairs of AI responses and rate which is more helpful, harmless, and honest. Provide brief explanations for your choices. Training provided.', budget: 350 },
  { category: 'ai_training', title: 'Write 20 diverse prompts for testing a chatbot', description: 'Create 20 varied prompts to test an AI chatbot covering: customer service, creative writing, coding help, and general knowledge. Include edge cases.', budget: 250 },

  { category: 'moderation', title: 'Review 300 user comments for policy violations', description: 'Review user comments and flag any that violate community guidelines (hate speech, spam, harassment). Categorize violations. Training on guidelines provided.', budget: 400 },
  { category: 'moderation', title: 'Check 100 product listings for prohibited items', description: 'Review e-commerce listings and identify any prohibited items (weapons, counterfeit goods, restricted substances). Flag and categorize violations.', budget: 350 },
];

async function createTasks() {
  const requesterId = await getTestRequester();
  if (!requesterId) {
    console.error('Test requester not found!');
    process.exit(1);
  }
  
  console.log('Creating tasks for requester:', requesterId);
  
  let created = 0;
  for (const task of tasks) {
    const { data, error } = await supabase.from('tasks').insert({
      requester_id: requesterId,
      title: task.title,
      description: task.description,
      category: task.category,
      budget: task.budget,
      max_workers: 2,
      current_workers: 0,
      status: 'active',
      is_local: task.is_local || false,
      location: task.location || null,
      competition_mode: 'quality',
      duration_days: 14,
      expires_at: new Date(Date.now() + 14 * 86400000).toISOString(),
    }).select().single();
    
    if (error) {
      console.error('Error creating task:', task.title, error.message);
    } else {
      created++;
      console.log('✅ Created:', task.title.substring(0, 50));
    }
  }
  
  console.log(`\n✅ Created ${created}/${tasks.length} tasks`);
  process.exit(0);
}

createTasks();
