/**
 * ═══════════════════════════════════════════════════════════════════════════════
 * LOOPUMAN TASK TEMPLATES
 * ═══════════════════════════════════════════════════════════════════════════════
 * 
 * Pre-built templates for common microtask types.
 * Makes it easy for requesters to post tasks quickly.
 * 
 * CATEGORIES:
 * - Data Entry
 * - Image Tasks
 * - Text Tasks
 * - Survey/Research
 * - Audio Tasks
 * - Verification
 * - Social Media
 * 
 * ═══════════════════════════════════════════════════════════════════════════════
 */

'use strict';

// ═══════════════════════════════════════════════════════════════════════════════
// TASK TEMPLATES
// ═══════════════════════════════════════════════════════════════════════════════

const TASK_TEMPLATES = {
  // ─────────────────────────────────────────────────────────────────────────────
  // DATA ENTRY
  // ─────────────────────────────────────────────────────────────────────────────
  data_entry: {
    category: 'Data Entry',
    emoji: '📝',
    templates: [
      {
        id: 'receipt_transcription',
        name: 'Receipt Transcription',
        description: 'Transcribe receipt details into structured format',
        instructions: 'Look at the receipt image and extract:\n1. Store name\n2. Date\n3. Items purchased (name, quantity, price)\n4. Total amount\n5. Payment method\n\nFormat as JSON.',
        estimated_time: 5,
        suggested_price: 50, // Ⓥ50 = $0.50
        fields: ['store_name', 'date', 'items', 'total', 'payment_method']
      },
      {
        id: 'business_card_entry',
        name: 'Business Card Data Entry',
        description: 'Enter business card information into database format',
        instructions: 'Extract from the business card:\n1. Full name\n2. Job title\n3. Company name\n4. Phone number(s)\n5. Email address\n6. Website\n7. Address',
        estimated_time: 3,
        suggested_price: 30,
        fields: ['name', 'title', 'company', 'phone', 'email', 'website', 'address']
      },
      {
        id: 'spreadsheet_entry',
        name: 'Spreadsheet Data Entry',
        description: 'Enter data from image/PDF into spreadsheet format',
        instructions: 'Transfer the data from the provided document into the specified format. Maintain accuracy and proper formatting.',
        estimated_time: 10,
        suggested_price: 100,
        fields: ['data']
      }
    ]
  },

  // ─────────────────────────────────────────────────────────────────────────────
  // IMAGE TASKS
  // ─────────────────────────────────────────────────────────────────────────────
  image: {
    category: 'Image Tasks',
    emoji: '🖼️',
    templates: [
      {
        id: 'image_tagging',
        name: 'Image Tagging',
        description: 'Add descriptive tags to images',
        instructions: 'Look at the image and provide 5-10 relevant tags that describe:\n1. Main subjects\n2. Actions/activities\n3. Setting/location\n4. Colors/style\n5. Mood/atmosphere',
        estimated_time: 2,
        suggested_price: 20,
        fields: ['tags']
      },
      {
        id: 'image_categorization',
        name: 'Image Categorization',
        description: 'Classify images into categories',
        instructions: 'View the image and select the most appropriate category from the provided options. If unsure, select "Other" and provide a suggested category.',
        estimated_time: 1,
        suggested_price: 10,
        fields: ['category', 'confidence', 'notes']
      },
      {
        id: 'object_detection',
        name: 'Object Bounding Boxes',
        description: 'Draw boxes around objects in images',
        instructions: 'Identify and mark all instances of the specified object(s) in the image. Draw tight bounding boxes around each instance.',
        estimated_time: 5,
        suggested_price: 50,
        fields: ['objects', 'bounding_boxes']
      },
      {
        id: 'image_comparison',
        name: 'Image Comparison',
        description: 'Compare two images and identify differences',
        instructions: 'Compare the two provided images and list all differences you can find. Be specific about location and nature of each difference.',
        estimated_time: 5,
        suggested_price: 50,
        fields: ['differences']
      },
      {
        id: 'image_quality',
        name: 'Image Quality Rating',
        description: 'Rate image quality and usability',
        instructions: 'Rate the image on:\n1. Clarity (1-5)\n2. Lighting (1-5)\n3. Composition (1-5)\n4. Overall quality (1-5)\n5. Suitable for: [web/print/social]',
        estimated_time: 2,
        suggested_price: 20,
        fields: ['clarity', 'lighting', 'composition', 'overall', 'suitable_for']
      }
    ]
  },

  // ─────────────────────────────────────────────────────────────────────────────
  // TEXT TASKS
  // ─────────────────────────────────────────────────────────────────────────────
  text: {
    category: 'Text Tasks',
    emoji: '📄',
    templates: [
      {
        id: 'sentiment_analysis',
        name: 'Sentiment Analysis',
        description: 'Determine the sentiment of text',
        instructions: 'Read the text and classify the sentiment as:\n- Positive\n- Negative\n- Neutral\n- Mixed\n\nAlso rate intensity (1-5) and explain your reasoning.',
        estimated_time: 2,
        suggested_price: 20,
        fields: ['sentiment', 'intensity', 'reasoning']
      },
      {
        id: 'text_summarization',
        name: 'Text Summarization',
        description: 'Summarize text in fewer words',
        instructions: 'Read the provided text and write a concise summary that:\n1. Captures main points\n2. Is 20-30% of original length\n3. Maintains key information\n4. Uses clear language',
        estimated_time: 10,
        suggested_price: 100,
        fields: ['summary']
      },
      {
        id: 'grammar_check',
        name: 'Grammar & Spelling Check',
        description: 'Find and correct grammar/spelling errors',
        instructions: 'Review the text for:\n1. Spelling errors\n2. Grammar mistakes\n3. Punctuation issues\n4. Awkward phrasing\n\nProvide corrected version and list of changes.',
        estimated_time: 5,
        suggested_price: 50,
        fields: ['corrected_text', 'changes']
      },
      {
        id: 'translation_review',
        name: 'Translation Quality Check',
        description: 'Review translation accuracy',
        instructions: 'Compare the original text with the translation and rate:\n1. Accuracy (1-5)\n2. Fluency (1-5)\n3. Tone preservation (1-5)\n\nNote any errors or improvements needed.',
        estimated_time: 10,
        suggested_price: 100,
        fields: ['accuracy', 'fluency', 'tone', 'errors', 'suggestions']
      },
      {
        id: 'content_moderation',
        name: 'Content Moderation',
        description: 'Check content for policy violations',
        instructions: 'Review the content and flag if it contains:\n- Hate speech\n- Violence\n- Adult content\n- Misinformation\n- Spam\n- Personal information\n\nProvide specific reasoning.',
        estimated_time: 3,
        suggested_price: 30,
        fields: ['flags', 'reasoning', 'severity']
      }
    ]
  },

  // ─────────────────────────────────────────────────────────────────────────────
  // SURVEY & RESEARCH
  // ─────────────────────────────────────────────────────────────────────────────
  survey: {
    category: 'Survey & Research',
    emoji: '📊',
    templates: [
      {
        id: 'simple_survey',
        name: 'Simple Survey',
        description: 'Answer survey questions',
        instructions: 'Answer all questions honestly based on your personal experience. There are no right or wrong answers.',
        estimated_time: 5,
        suggested_price: 50,
        fields: ['responses']
      },
      {
        id: 'product_feedback',
        name: 'Product Feedback',
        description: 'Provide feedback on a product/service',
        instructions: 'Review the product/service and provide:\n1. Overall rating (1-5)\n2. Likes (at least 3)\n3. Dislikes (at least 2)\n4. Improvement suggestions\n5. Would you recommend? Why/why not?',
        estimated_time: 10,
        suggested_price: 100,
        fields: ['rating', 'likes', 'dislikes', 'suggestions', 'recommend']
      },
      {
        id: 'website_review',
        name: 'Website Usability Review',
        description: 'Review website usability and design',
        instructions: 'Visit the website and evaluate:\n1. First impression (1-5)\n2. Navigation ease (1-5)\n3. Design quality (1-5)\n4. Mobile friendliness (1-5)\n5. Load speed\n6. Suggestions for improvement',
        estimated_time: 15,
        suggested_price: 150,
        fields: ['first_impression', 'navigation', 'design', 'mobile', 'speed', 'suggestions']
      },
      {
        id: 'competitor_research',
        name: 'Competitor Research',
        description: 'Research competitor information',
        instructions: 'Research the specified competitor and provide:\n1. Key products/services\n2. Pricing information\n3. Unique selling points\n4. Social media presence\n5. Recent news/updates',
        estimated_time: 20,
        suggested_price: 200,
        fields: ['products', 'pricing', 'usp', 'social', 'news']
      }
    ]
  },

  // ─────────────────────────────────────────────────────────────────────────────
  // AUDIO TASKS
  // ─────────────────────────────────────────────────────────────────────────────
  audio: {
    category: 'Audio Tasks',
    emoji: '🎧',
    templates: [
      {
        id: 'audio_transcription',
        name: 'Audio Transcription',
        description: 'Transcribe audio to text',
        instructions: 'Listen to the audio clip and transcribe exactly what is said. Include:\n- Speaker labels if multiple speakers\n- Timestamps every 30 seconds\n- [inaudible] for unclear parts\n- [noise/music] for non-speech sounds',
        estimated_time: 15,
        suggested_price: 150,
        fields: ['transcription']
      },
      {
        id: 'audio_quality',
        name: 'Audio Quality Rating',
        description: 'Rate audio quality',
        instructions: 'Listen to the audio and rate:\n1. Clarity (1-5)\n2. Volume level (too quiet/good/too loud)\n3. Background noise level (1-5, 5=silent)\n4. Overall quality (1-5)\n5. Suitable for: [podcast/video/call]',
        estimated_time: 3,
        suggested_price: 30,
        fields: ['clarity', 'volume', 'noise', 'overall', 'suitable_for']
      },
      {
        id: 'speech_sentiment',
        name: 'Speech Sentiment Analysis',
        description: 'Analyze sentiment in spoken audio',
        instructions: 'Listen to the audio and identify:\n1. Overall sentiment (positive/negative/neutral)\n2. Emotional tone (happy/sad/angry/calm/etc.)\n3. Key emotional moments with timestamps\n4. Confidence level in your assessment',
        estimated_time: 5,
        suggested_price: 50,
        fields: ['sentiment', 'tone', 'moments', 'confidence']
      }
    ]
  },

  // ─────────────────────────────────────────────────────────────────────────────
  // VERIFICATION TASKS
  // ─────────────────────────────────────────────────────────────────────────────
  verification: {
    category: 'Verification',
    emoji: '✅',
    templates: [
      {
        id: 'data_verification',
        name: 'Data Verification',
        description: 'Verify accuracy of data',
        instructions: 'Compare the provided data against the source and verify:\n1. All fields match\n2. No spelling errors\n3. Formatting is correct\n4. Data is complete\n\nMark any discrepancies.',
        estimated_time: 5,
        suggested_price: 50,
        fields: ['verified', 'discrepancies']
      },
      {
        id: 'contact_verification',
        name: 'Contact Information Verification',
        description: 'Verify contact details are correct',
        instructions: 'Verify the contact information by:\n1. Checking website for correct email/phone\n2. Confirming business address\n3. Verifying social media links work\n\nReport status of each field.',
        estimated_time: 10,
        suggested_price: 100,
        fields: ['email_status', 'phone_status', 'address_status', 'social_status']
      },
      {
        id: 'link_verification',
        name: 'Link Verification',
        description: 'Check if links are working',
        instructions: 'Test each provided link and report:\n1. Working (200 OK)\n2. Broken (404 or error)\n3. Redirect (note destination)\n4. Slow (>5 seconds)\n5. Blocked (requires login/payment)',
        estimated_time: 5,
        suggested_price: 50,
        fields: ['link_results']
      }
    ]
  },

  // ─────────────────────────────────────────────────────────────────────────────
  // SOCIAL MEDIA
  // ─────────────────────────────────────────────────────────────────────────────
  social: {
    category: 'Social Media',
    emoji: '📱',
    templates: [
      {
        id: 'social_engagement',
        name: 'Social Media Engagement Analysis',
        description: 'Analyze social media post engagement',
        instructions: 'Review the social media post and analyze:\n1. Engagement metrics (likes, comments, shares)\n2. Comment sentiment breakdown\n3. Top performing elements\n4. Improvement suggestions',
        estimated_time: 10,
        suggested_price: 100,
        fields: ['metrics', 'sentiment', 'top_elements', 'suggestions']
      },
      {
        id: 'hashtag_research',
        name: 'Hashtag Research',
        description: 'Research relevant hashtags for topic',
        instructions: 'Research and provide:\n1. 10 highly relevant hashtags\n2. 5 trending hashtags\n3. 5 niche hashtags\n4. Estimated reach for each\n5. Competition level (high/medium/low)',
        estimated_time: 15,
        suggested_price: 150,
        fields: ['relevant', 'trending', 'niche', 'reach', 'competition']
      },
      {
        id: 'influencer_research',
        name: 'Influencer Profile Research',
        description: 'Research social media influencer',
        instructions: 'Research the influencer and provide:\n1. Follower count (all platforms)\n2. Engagement rate\n3. Content style/niche\n4. Audience demographics (estimated)\n5. Brand collaboration history\n6. Contact information (if public)',
        estimated_time: 20,
        suggested_price: 200,
        fields: ['followers', 'engagement', 'style', 'demographics', 'collaborations', 'contact']
      }
    ]
  }
};

// ═══════════════════════════════════════════════════════════════════════════════
// HELPER FUNCTIONS
// ═══════════════════════════════════════════════════════════════════════════════

/**
 * Get all categories with their emoji
 */
function getCategories() {
  return Object.entries(TASK_TEMPLATES).map(([key, cat]) => ({
    id: key,
    name: cat.category,
    emoji: cat.emoji,
    templateCount: cat.templates.length
  }));
}

/**
 * Get templates for a category
 */
function getTemplatesForCategory(categoryId) {
  const category = TASK_TEMPLATES[categoryId];
  if (!category) return null;
  
  return {
    category: category.category,
    emoji: category.emoji,
    templates: category.templates.map(t => ({
      id: t.id,
      name: t.name,
      description: t.description,
      estimated_time: t.estimated_time,
      suggested_price: t.suggested_price
    }))
  };
}

/**
 * Get full template details
 */
function getTemplate(categoryId, templateId) {
  const category = TASK_TEMPLATES[categoryId];
  if (!category) return null;
  
  const template = category.templates.find(t => t.id === templateId);
  if (!template) return null;
  
  return {
    ...template,
    category: category.category,
    categoryId,
    emoji: category.emoji
  };
}

/**
 * Generate task from template
 */
function generateTaskFromTemplate(categoryId, templateId, customizations = {}) {
  const template = getTemplate(categoryId, templateId);
  if (!template) return null;
  
  return {
    title: customizations.title || template.name,
    description: customizations.description || template.description,
    instructions: customizations.instructions || template.instructions,
    category: template.category,
    estimated_time_minutes: customizations.estimated_time || template.estimated_time,
    budget_vae: customizations.budget_vae || template.suggested_price,
    required_fields: template.fields,
    template_id: templateId,
    ...customizations
  };
}

/**
 * Get template display text for Telegram
 */
function getTemplateDisplayText(categoryId, templateId) {
  const template = getTemplate(categoryId, templateId);
  if (!template) return 'Template not found';
  
  let text = `${template.emoji} *${template.name}*\n\n`;
  text += `📝 ${template.description}\n\n`;
  text += `⏱ Estimated time: ${template.estimated_time} minutes\n`;
  text += `💰 Suggested price: Ⓥ${template.suggested_price} ($${(template.suggested_price/100).toFixed(2)})\n\n`;
  text += `*Instructions:*\n${template.instructions}`;
  
  return text;
}

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

module.exports = {
  TASK_TEMPLATES,
  getCategories,
  getTemplatesForCategory,
  getTemplate,
  generateTaskFromTemplate,
  getTemplateDisplayText
};
