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

const IMAGES = {
  product_sneakers: 'https://images.unsplash.com/photo-1542291026-7eec264c27ff?w=800',
  product_bottles: 'https://images.unsplash.com/photo-1602143407151-7111542de6e8?w=800',
  handwritten_notes: 'https://images.unsplash.com/photo-1517842645767-c639042777db?w=800',
  restaurant_menu: 'https://images.unsplash.com/photo-1568901346375-23c9450c58cd?w=800',
  food_plate: 'https://images.unsplash.com/photo-1546069901-ba9599a7e63c?w=800',
  coffee_shop: 'https://images.unsplash.com/photo-1509042239860-f550ce710b93?w=800',
  storefront: 'https://images.unsplash.com/photo-1528698827591-e19cef3a72f7?w=800',
  spreadsheet: 'https://images.unsplash.com/photo-1551288049-bebda4e38f71?w=800',
  dashboard: 'https://images.unsplash.com/photo-1460925895917-afdab827c52f?w=800',
  street_scene: 'https://images.unsplash.com/photo-1477959858617-67f85cf4f1df?w=800',
  parking_lot: 'https://images.unsplash.com/photo-1590674899484-d5640e854abe?w=800',
  mobile_app: 'https://images.unsplash.com/photo-1512941937669-90a1b58e7e9c?w=800',
  website_screenshot: 'https://images.unsplash.com/photo-1547658719-da2b51169166?w=800',
  customer_service: 'https://images.unsplash.com/photo-1556745757-8d76bdb6984b?w=800',
  audio_waveform: 'https://images.unsplash.com/photo-1478737270239-2f02b77fc618?w=800',
  foreign_text: 'https://images.unsplash.com/photo-1456513080510-7bf3a84b82f8?w=800',
  ai_robot: 'https://images.unsplash.com/photo-1485827404703-89b55fcc595e?w=800',
  chatbot_screen: 'https://images.unsplash.com/photo-1531746790095-e5e5067303f0?w=800',
  meeting_room: 'https://images.unsplash.com/photo-1497366216548-37526070297c?w=800',
};

function media(url, filename) { return { type: 'image', url, filename }; }

const TASKS = [
  { title:'Label 200 street images for autonomous driving dataset', description:'Label street-scene images for a self-driving car AI project.\n\nWhat to do:\n1. Open the labeling tool link provided\n2. For each image, draw bounding boxes around: cars, pedestrians, traffic signs, lane markings\n3. Label each box with the correct category\n4. Flag any ambiguous images\n\nQuality: 95%+ accuracy, tight boxes, dont skip partial objects.', category:'labeling', budget:1500, max_workers:3, is_local:false, duration_days:7, reference_media:[media(IMAGES.street_scene,'example_street_scene.jpg'),media(IMAGES.parking_lot,'labeling_format.jpg')] },
  { title:'Categorize 500 product images by type and color', description:'Review each product image and assign:\n- Primary category (Clothing, Electronics, Home, Food, Beauty)\n- Primary color\n- Flag low-quality or duplicate images\n\nSpreadsheet with image links shared after acceptance.', category:'labeling', budget:800, max_workers:2, is_local:false, duration_days:5, reference_media:[media(IMAGES.product_sneakers,'sample_product.jpg'),media(IMAGES.spreadsheet,'category_format.jpg')] },
  { title:'Write 8 product descriptions for an online sneaker store', description:'Write compelling product descriptions for our sneaker e-commerce site.\n\nFor each sneaker:\n- 120-150 words\n- Highlight comfort, style, durability\n- Catchy headline\n- Target: 18-35 urban fashion buyers\n- SEO keywords: sneakers, comfortable, streetwear\n\nTone: Energetic, youthful, confident.', category:'writing', budget:500, max_workers:2, is_local:false, duration_days:4, reference_media:[media(IMAGES.product_sneakers,'sneaker_style_reference.jpg')] },
  { title:'Write a 1500-word blog post about remote work productivity', description:'Write an engaging blog post about remote work productivity tips.\n\n- 1500 words minimum\n- At least 5 actionable tips\n- Include a personal anecdote\n- Subheadings for readability\n- Reference 2 real studies\n- End with call to action\n\nStyle: Conversational, helpful, not preachy.', category:'writing', budget:600, max_workers:1, is_local:false, duration_days:3, reference_media:[media(IMAGES.website_screenshot,'blog_layout_reference.jpg')] },
  { title:'Research top 10 coffee shops in Nairobi with contact details', description:'Find the top 10 highest-rated coffee shops in Nairobi.\n\nFor each provide:\n- Business name, Google Maps rating, reviews count\n- Full address, phone number\n- Instagram/social handle\n- Opening hours, price range\n- One signature drink\n\nDeliver as formatted list or spreadsheet.', category:'research', budget:400, max_workers:1, is_local:false, duration_days:3, reference_media:[media(IMAGES.coffee_shop,'example_coffee_shop.jpg'),media(IMAGES.dashboard,'data_format.jpg')] },
  { title:'Competitive analysis: 5 food delivery apps in Lagos', description:'Research top 5 food delivery apps in Lagos.\n\nFor each document:\n- App name, download count\n- Pricing model, delivery fee, minimum order\n- Average delivery time\n- Number of restaurants\n- Payment methods\n- User ratings Play Store & App Store\n- Unique features\n\nDeliverable: Comparison table + 200-word summary.', category:'research', budget:700, max_workers:1, is_local:false, duration_days:5, reference_media:[media(IMAGES.mobile_app,'app_screenshot.jpg')] },
  { title:'Verify 50 business email addresses are still active', description:'Verify 50 business email addresses.\n\n1. Visit each company website\n2. Check email domain matches company\n3. Look for person on LinkedIn\n4. Mark: Verified / Uncertain / Invalid\n\nDeliverable: Updated spreadsheet with status and notes.', category:'verification', budget:500, max_workers:1, is_local:false, duration_days:3, reference_media:[media(IMAGES.spreadsheet,'email_list_format.jpg')] },
  { title:'Verify product listings match actual items (e-commerce QA)', description:'Verify product listings match photos.\n\nCheck each listing:\n- Title matches photo?\n- Price reasonable?\n- Dimensions correct?\n- Typos in description?\n- Category makes sense?\n\nFlag mismatches in template provided.', category:'verification', budget:600, max_workers:2, is_local:false, duration_days:4, reference_media:[media(IMAGES.product_bottles,'sample_listing.jpg')] },
  { title:'Complete a 15-minute survey about mobile banking habits', description:'Research survey on mobile banking usage in Africa.\n\nTopics: apps used, frequency, frustrations, desired features, comfort with crypto.\n\nRequirements:\n- Must be 18+\n- Active mobile banking user\n- Thoughtful answers\n- Takes ~15 minutes\n\nSurvey link shared after acceptance.', category:'survey', budget:200, max_workers:10, is_local:false, duration_days:7, reference_media:[media(IMAGES.mobile_app,'mobile_banking_ref.jpg')] },
  { title:'Test our new app and provide detailed UX feedback', description:'Download beta app and complete 5 tasks, then fill feedback form.\n\nTasks: Create account, browse feed, test purchase, leave review, use search.\n\nFor each report: time to complete, confusion/errors, likes, improvements, bug screenshots.', category:'survey', budget:350, max_workers:5, is_local:false, duration_days:5, reference_media:[media(IMAGES.mobile_app,'beta_app_preview.jpg'),media(IMAGES.website_screenshot,'feedback_template.jpg')] },
  { title:'Rate 100 AI chatbot responses for helpfulness and accuracy', description:'Rate AI assistant responses on 3 dimensions (1-5):\n- Helpfulness\n- Accuracy\n- Tone\n\nWrite 1-sentence note if rating below 3. Flag harmful responses immediately.\n\nEach set of 100 takes ~90 minutes. Be honest, not generous.', category:'ai_training', budget:1200, max_workers:3, is_local:false, duration_days:5, reference_media:[media(IMAGES.chatbot_screen,'rating_interface.jpg'),media(IMAGES.ai_robot,'ai_training_overview.jpg')] },
  { title:'Write 50 diverse prompts to test an AI image generator', description:'Create 50 unique prompts for AI image generator.\n\nCover styles: photorealistic, cartoon, abstract, fantasy, architectural.\nInclude specific details (lighting, colors, composition).\nRange from simple to complex.\nAt least 10 with diverse ethnicities.\nNo NSFW.\n\nDeliverable: Text file with numbered prompts.', category:'ai_training', budget:500, max_workers:2, is_local:false, duration_days:4, reference_media:[media(IMAGES.ai_robot,'ai_image_examples.jpg')] },
  { title:'Translate a 2-page product brochure from English to Swahili', description:'Translate product brochure English to Swahili (Kenyan dialect).\n\n- ~800 words\n- Maintain marketing tone\n- Localize currency (USD to KES)\n- Keep brand names untranslated\n- Proofread for natural flow\n\nQualifications: Native Swahili, fluent English.', category:'translation', budget:600, max_workers:1, is_local:false, duration_days:3, reference_media:[media(IMAGES.foreign_text,'brochure_english.jpg')] },
  { title:'Translate 20 customer reviews from French to English', description:'Translate 20 French customer reviews to English.\n\n- Preserve emotional tone\n- Dont improve reviews, translate as-is\n- Flag profanity\n- Add sentiment tag: Positive / Neutral / Negative\n\nDeliverable: Spreadsheet with French + English + sentiment.', category:'translation', budget:400, max_workers:1, is_local:false, duration_days:4, reference_media:[media(IMAGES.foreign_text,'french_reviews.jpg')] },
  { title:'Review 300 user comments for community guideline violations', description:'Moderate user comments. Flag:\n- Hate speech, discrimination\n- Personal attacks, bullying\n- Spam, self-promotion\n- Misinformation\n- Graphic violence\n- Personal information\n\nFor each: violation category, severity (Low/Medium/High), action (Warn/Remove/Ban).', category:'moderation', budget:1000, max_workers:2, is_local:false, duration_days:3, reference_media:[media(IMAGES.customer_service,'moderation_dashboard.jpg'),media(IMAGES.dashboard,'flagging_categories.jpg')] },
  { title:'Check 100 product listings for prohibited items', description:'Review marketplace listings for policy violations.\n\nProhibited: counterfeit goods, weapons, medications, stolen property, misleading claims.\n\nMark each: Approved / Needs review / Remove (with explanation).', category:'moderation', budget:800, max_workers:2, is_local:false, duration_days:4, reference_media:[media(IMAGES.product_bottles,'marketplace_listing.jpg')] },
  { title:'Transcribe a 30-minute business podcast episode', description:'Transcribe 30-minute fintech podcast.\n\n- Verbatim (include ums, pauses)\n- Speaker ID (Host + Guest)\n- Timestamps every 2 minutes\n- Mark unclear audio [inaudible]\n- Include [laughs], [pause], [crosstalk]\n\nFormat: [00:00] Host: Welcome to...\n\nAudio link shared after acceptance.', category:'transcription', budget:700, max_workers:1, is_local:false, duration_days:3, reference_media:[media(IMAGES.audio_waveform,'podcast_preview.jpg'),media(IMAGES.handwritten_notes,'transcription_format.jpg')] },
  { title:'Convert handwritten meeting notes to digital text', description:'Type up 15 pages of handwritten meeting notes.\n\n- Convert to clean structured text\n- Organize by topic/heading\n- Mark illegible sections [unclear]\n- Fix obvious spelling errors\n\nDeliverable: Word document or Google Doc.', category:'transcription', budget:450, max_workers:1, is_local:false, duration_days:4, reference_media:[media(IMAGES.handwritten_notes,'sample_notes.jpg')] },
  { title:'Sign up for 3 newsletters and confirm email subscriptions', description:'Test newsletter signup flows for 3 websites.\n\nFor each:\n1. Go to URL\n2. Find signup form\n3. Enter email and subscribe\n4. Check email for confirmation\n5. Click confirmation link\n6. Screenshot confirmation page\n\nDeliverable: 3 screenshots of confirmed subscriptions.', category:'micro', budget:150, max_workers:3, is_local:false, duration_days:2, reference_media:[media(IMAGES.website_screenshot,'newsletter_example.jpg')] },
  { title:'Download and test 2 mobile apps, rate them on Play Store', description:'Download 2 apps from Play Store, use 10 mins each, leave honest review.\n\nFor each:\n1. Download and create account\n2. Use main features 10 minutes\n3. Leave star rating + 50-word review\n4. Screenshot your review\n\nReviews must be honest. App names shared after acceptance.', category:'micro', budget:200, max_workers:5, is_local:false, duration_days:3, reference_media:[media(IMAGES.mobile_app,'app_review_example.jpg')] },
  { title:'Take 10 photos of menu boards at local coffee shops', description:'Visit coffee shops and photograph menu boards.\n\n- Visit at least 3 different shops\n- Clear readable photos of menus with prices\n- 1 exterior photo per shop\n- Note shop name and location\n\nPhoto quality: Good lighting, no blur, full menu visible, prices readable.\n\nDeliverable: 10+ photos with names and addresses.', category:'local', budget:400, max_workers:3, is_local:true, duration_days:5, location:{lat:-1.2921,lng:36.8219,radius:10000}, reference_media:[media(IMAGES.coffee_shop,'coffee_shop_example.jpg'),media(IMAGES.restaurant_menu,'menu_quality_guide.jpg')] },
  { title:'Check product availability at 3 supermarkets', description:'Visit 3 supermarkets and check if specific products are in stock.\n\nProducts (list after acceptance): 5 snack brands, 3 beverages, 2 household items.\n\nFor each store:\n1. Check shelf availability\n2. Note price displayed\n3. Photo of shelf section\n4. Note any sale/promotion\n\nDeliverable: Completed checklist + photos.', category:'local', budget:500, max_workers:2, is_local:true, duration_days:4, location:{lat:-1.2921,lng:36.8219,radius:15000}, reference_media:[media(IMAGES.storefront,'supermarket_ref.jpg'),media(IMAGES.spreadsheet,'checklist.jpg')] },
  { title:'Mystery shop a mobile phone store experience', description:'Visit a mobile phone store (Safaricom/Airtel) and evaluate:\n\n1. Greeting within 2 minutes?\n2. Product knowledge (ask about a model)\n3. Sales approach: pushy or helpful?\n4. Store cleanliness\n5. Wait time\n6. Overall satisfaction (1-10)\n\nScenario: Looking for smartphone under KES 30,000, ask about payment plans.\n\nDeliverable: Evaluation form + 2-3 discreet photos.', category:'mystery', budget:600, max_workers:2, is_local:true, duration_days:5, location:{lat:-1.2921,lng:36.8219,radius:20000}, reference_media:[media(IMAGES.storefront,'phone_store_ref.jpg'),media(IMAGES.customer_service,'evaluation_criteria.jpg')] },
  { title:'Evaluate customer service at a fast food restaurant', description:'Visit a fast food restaurant (KFC/Pizza Inn/Chicken Inn) and rate experience.\n\n1. Order a meal (reimbursement up to V300)\n2. Time the order\n3. Check food quality and presentation\n4. Evaluate staff friendliness\n5. Check restroom cleanliness\n6. Note health/safety concerns\n\nAct naturally - dont reveal you are evaluating!\n\nDeliverable: Mystery shop form + meal photos.', category:'mystery', budget:800, max_workers:2, is_local:true, duration_days:5, location:{lat:6.5244,lng:3.3792,radius:20000}, reference_media:[media(IMAGES.food_plate,'food_quality_ref.jpg'),media(IMAGES.restaurant_menu,'scoring_rubric.jpg')] },
  { title:'Create 5 sample customer personas for an e-commerce store', description:'Create 5 fictional customer personas for online fashion store targeting African millennials.\n\nFor each:\n- Name, age, city, occupation\n- Income range\n- Shopping habits\n- Fashion preferences\n- Pain points online shopping\n- What makes them loyal\n- Short quote capturing attitude\n\nMake diverse across gender, income, location.', category:'other', budget:500, max_workers:1, is_local:false, duration_days:4, reference_media:[media(IMAGES.dashboard,'persona_template.jpg'),media(IMAGES.meeting_room,'target_audience.jpg')] },
  { title:'Organize and rename 100 product images following naming convention', description:'Rename 100 product images following convention:\n[category]-[product-name]-[color]-[angle].jpg\n\nExamples:\nshoes-nike-airmax-black-front.jpg\nbags-leather-tote-brown-side.jpg\n\nAlso: remove duplicates, flag images under 500px, create CSV mapping old to new filenames.', category:'other', budget:350, max_workers:1, is_local:false, duration_days:3, reference_media:[media(IMAGES.product_sneakers,'naming_convention.jpg')] },
];

async function seedTasks() {
  console.log('Loopuman - Seeding Realistic Test Tasks with Attachments');
  console.log('='.repeat(60));
  let requesterId;
  const { data: existingUser } = await supabase.from('app_users').select('id, username, first_name').or('username.eq.Agentic888,username.eq.test_requester').limit(1).maybeSingle();
  if (existingUser) {
    requesterId = existingUser.id;
    console.log('Using requester:', existingUser.username || existingUser.first_name, '(' + requesterId + ')');
  } else {
    const { data: anyUser } = await supabase.from('app_users').select('id, username').limit(1).single();
    if (anyUser) { requesterId = anyUser.id; console.log('Fallback requester:', anyUser.username); }
    else { console.error('No users found!'); return; }
  }
  const { data: balance } = await supabase.from('vae_balances').select('deposit_balance').eq('user_id', requesterId).maybeSingle();
  const totalCost = TASKS.reduce((s, t) => s + t.budget, 0);
  console.log('\nBudget needed: V' + totalCost + ' | Current: V' + (balance?.deposit_balance || 0));
  if ((balance?.deposit_balance || 0) < totalCost) {
    const topUp = totalCost + 5000;
    await supabase.from('vae_balances').upsert({ user_id: requesterId, deposit_balance: topUp }, { onConflict: 'user_id' });
    console.log('Topped up to V' + topUp);
  }
  console.log('\nCreating tasks...\n');
  let created = 0;
  const cats = {};
  for (const t of TASKS) {
    const { data, error } = await supabase.from('tasks').insert({
      requester_id: requesterId, title: t.title, description: t.description, category: t.category,
      budget: t.budget, max_workers: t.max_workers || 2, current_workers: 0, is_local: t.is_local || false,
      duration_days: t.duration_days || 7, status: 'active', reference_media: t.reference_media || [],
      location: t.location || null, requires_gps: t.is_local || false,
      expires_at: new Date(Date.now() + (t.duration_days || 14) * 86400000).toISOString(),
      competition_mode: (t.max_workers || 2) > 1 ? 'quality' : null,
    }).select('id, title, category').single();
    if (error) { console.log('FAIL:', t.title.substring(0,50), error.message); }
    else { cats[t.category] = (cats[t.category] || 0) + 1; created++; console.log('[' + t.category + '] ' + data.title.substring(0,55) + ' (' + (t.reference_media?.length||0) + ' files)'); }
  }
  console.log('\n' + '='.repeat(60));
  console.log('Created ' + created + '/' + TASKS.length + ' tasks\n');
  const allCats = ['labeling','writing','research','verification','survey','ai_training','translation','moderation','transcription','micro','local','mystery','other'];
  allCats.forEach(c => console.log((cats[c]?'OK':'XX') + ' ' + c + ': ' + (cats[c]||0)));
  console.log('\nTotal attachments: ' + TASKS.reduce((s,t) => s + (t.reference_media?.length||0), 0));
}
seedTasks().catch(console.error).finally(() => process.exit(0));
