// ai-verification-engine.js
// Worker skill verification using AI vision and text analysis

const fs = require('fs');
const path = require('path');

class AIVerificationEngine {
  constructor(aiClient) {
    this.ai = aiClient; // Your DeepSeek/OpenAI client
  }

  /**
   * Parse CV/Resume and extract structured data
   */
  async parseResumeFromText(textContent) {
    try {
      const prompt = 'Analyze this CV/resume text and extract structured data. Return ONLY valid JSON with keys: name, skills, experience_years, languages, education, summary. CV Text: ' + textContent.slice(0, 3000);
      const response = await this.ai.chat.completions.create({
        model: 'deepseek-chat',
        messages: [{ role: 'user', content: prompt }],
        max_tokens: 500,
      });
      const raw = response.choices[0]?.message?.content?.trim() || '{}';
      const cleaned = raw.replace(/```json/g, '').replace(/```/g, '').trim();
      return JSON.parse(cleaned);
    } catch (e) {
      console.error('[AI] Resume parse error:', e.message);
      return null;
    }
  }

  async parseResume(imageBase64, mimeType = 'image/jpeg') {
    const prompt = `You are analyzing a CV/Resume image. Extract ALL structured data you can see.

Return ONLY valid JSON (no markdown, no explanation):
{
  "name": "Full name if visible",
  "title": "Current/most recent job title",
  "summary": "Brief 1-2 sentence professional summary",
  "skills": [
    {
      "name": "Exact skill name (standardize: e.g., 'MS Excel' → 'Microsoft Excel')",
      "category": "technical|language|creative|data|business|local|audio|research",
      "proficiency": "beginner|intermediate|expert",
      "years": null
    }
  ],
  "experience": [
    {
      "title": "Job title",
      "company": "Company name",
      "duration_months": 12,
      "skills_used": ["skill1", "skill2"]
    }
  ],
  "languages": [
    {"language": "English", "proficiency": "native|fluent|intermediate|basic"}
  ],
  "education": [
    {"degree": "...", "institution": "...", "year": 2020}
  ],
  "certifications": ["Cert name"],
  "contact": {
    "email": "if visible",
    "phone": "if visible", 
    "location": "city/country if visible"
  }
}

IMPORTANT:
- Extract ALL skills you can infer from job descriptions, not just explicitly listed
- Standardize skill names (e.g., "good with computers" → "Computer Skills")
- If something isn't visible, use null
- Be thorough - this affects the worker's opportunities`;

    const response = await this.ai.chat.completions.create({
      model: 'deepseek-chat', // or gpt-4-vision-preview
      messages: [
        {
          role: 'user',
          content: [
            { type: 'text', text: prompt },
            { 
              type: 'image_url', 
              image_url: { url: `data:${mimeType};base64,${imageBase64}` }
            }
          ]
        }
      ],
      max_tokens: 2000,
      temperature: 0.1
    });

    try {
      const content = response.choices[0].message.content;
      // Clean potential markdown code blocks
      const cleaned = content.replace(/```json\n?|\n?```/g, '').trim();
      return JSON.parse(cleaned);
    } catch (e) {
      console.error('CV parse error:', e);
      return null;
    }
  }

  /**
   * Verify LinkedIn screenshot and extract profile data
   */
  async verifyLinkedInScreenshot(imageBase64, claimedUrl) {
    const prompt = `Analyze this screenshot claimed to be from LinkedIn profile: ${claimedUrl}

Your task:
1. Verify this is a genuine LinkedIn screenshot (look for: LinkedIn logo, blue/white UI, profile layout, "Connect" button, endorsement badges)
2. Check if visible URL/username matches the claimed URL
3. Extract all visible profile information

Return ONLY valid JSON:
{
  "is_valid_linkedin": true,
  "url_matches": true,
  "confidence": 85,
  "profile_data": {
    "name": "Person's name",
    "headline": "Their headline/title",
    "location": "Location if shown",
    "connections": "500+" or number,
    "profile_photo_visible": true,
    "skills": [
      {"name": "Skill", "endorsements": 10}
    ],
    "experience": [
      {"title": "...", "company": "...", "current": true}
    ],
    "education": ["University name"],
    "verification_badges": ["premium", "verified_email"]
  },
  "red_flags": [],
  "rejection_reason": null
}

RED FLAGS to check:
- Screenshot looks edited/photoshopped
- UI doesn't match LinkedIn design
- Username in screenshot doesn't match claimed URL
- Suspiciously perfect or templated content
- Browser dev tools visible (could be edited)

Be strict but fair. If something looks off, add to red_flags.`;

    const response = await this.ai.chat.completions.create({
      model: 'deepseek-chat',
      messages: [
        {
          role: 'user',
          content: [
            { type: 'text', text: prompt },
            { 
              type: 'image_url', 
              image_url: { url: `data:image/jpeg;base64,${imageBase64}` }
            }
          ]
        }
      ],
      max_tokens: 1500,
      temperature: 0.1
    });

    try {
      const content = response.choices[0].message.content;
      const cleaned = content.replace(/```json\n?|\n?```/g, '').trim();
      return JSON.parse(cleaned);
    } catch (e) {
      console.error('LinkedIn verify error:', e);
      return { is_valid_linkedin: false, rejection_reason: 'Failed to analyze screenshot' };
    }
  }

  /**
   * Verify freelance platform screenshot (Upwork, Fiverr, Freelancer)
   */
  async verifyFreelancePlatform(imageBase64, platform, claimedUsername) {
    const platformInfo = {
      upwork: {
        name: 'Upwork',
        markers: 'Green color scheme (#14a800), JSS (Job Success Score) percentage, hourly rate in USD, "Top Rated" badge, "Available now" toggle, earned amount, profile completion',
        metrics: 'JSS score, hourly rate, jobs completed, total earned, hours worked'
      },
      fiverr: {
        name: 'Fiverr',
        markers: 'Green accent color (#1dbf73), seller levels (New Seller/Level 1/Level 2/Top Rated), star ratings, response rate, order completion, "Online" status',
        metrics: 'Rating, reviews count, orders completed, response rate, delivery time'
      },
      freelancer: {
        name: 'Freelancer',
        markers: 'Blue theme (#0e1724), reputation score with percentage, reviews count, "Preferred Freelancer" badge, earnings display',
        metrics: 'Reputation percentage, reviews, jobs completed, earnings'
      }
    };

    const info = platformInfo[platform.toLowerCase()];
    if (!info) return { is_valid_platform: false, rejection_reason: 'Unknown platform' };

    const prompt = `Analyze this screenshot claimed to be from ${info.name} for username: ${claimedUsername}

Platform visual markers to look for: ${info.markers}
Key metrics to extract: ${info.metrics}

Return ONLY valid JSON:
{
  "is_valid_platform": true,
  "platform": "${platform}",
  "username_visible": "actual username shown",
  "username_matches": true,
  "confidence": 80,
  "metrics": {
    "rating": 4.9,
    "reviews_count": 150,
    "jobs_completed": 200,
    "success_rate": 95,
    "member_since": "2020",
    "level": "Top Rated",
    "response_rate": 98,
    "hourly_rate": 25,
    "total_earned": "$10,000+",
    "skills_listed": ["skill1", "skill2"]
  },
  "red_flags": [],
  "rejection_reason": null
}

RED FLAGS:
- UI doesn't match ${info.name} design
- Username doesn't match claimed
- Screenshot appears edited
- Metrics look unrealistic (e.g., 1000% completion rate)
- Dev tools visible

Extract whatever metrics are visible. Use null for non-visible fields.`;

    const response = await this.ai.chat.completions.create({
      model: 'deepseek-chat',
      messages: [
        {
          role: 'user',
          content: [
            { type: 'text', text: prompt },
            { 
              type: 'image_url', 
              image_url: { url: `data:image/jpeg;base64,${imageBase64}` }
            }
          ]
        }
      ],
      max_tokens: 1500,
      temperature: 0.1
    });

    try {
      const content = response.choices[0].message.content;
      const cleaned = content.replace(/```json\n?|\n?```/g, '').trim();
      return JSON.parse(cleaned);
    } catch (e) {
      console.error('Platform verify error:', e);
      return { is_valid_platform: false, rejection_reason: 'Failed to analyze screenshot' };
    }
  }

  /**
   * Extract skills from free-text description (enhanced version)
   */
  async extractSkillsFromText(description) {
    const prompt = `Extract professional skills from this worker's self-description:

"${description}"

Categorize each skill into:
- language: Spoken/written human languages (English, Spanish, etc.)
- technical: Programming, software, tools, IT
- creative: Design, writing, content creation, video
- data: Data entry, analysis, labeling, annotation
- local: Location-dependent tasks (photography, delivery, in-person)
- audio: Transcription, voice work, translation
- research: Web research, fact-checking, lead generation
- business: Customer service, sales, admin, virtual assistance

Return ONLY valid JSON array:
[
  {
    "name": "Standardized Skill Name",
    "category": "category_from_above",
    "proficiency": "beginner|intermediate|expert",
    "confidence": 35,
    "raw_mention": "what they actually said"
  }
]

RULES:
- Standardize names: "good at excel" → "Microsoft Excel"
- Infer proficiency from context ("5 years experience" → expert)
- Set confidence 30-50 (self-reported baseline)
- Include ALL mentioned skills, even vague ones
- If they mention years, boost confidence to 40-50`;

    const response = await this.ai.chat.completions.create({
      model: 'deepseek-chat',
      messages: [{ role: 'user', content: prompt }],
      max_tokens: 1000,
      temperature: 0.2
    });

    try {
      const content = response.choices[0].message.content;
      const cleaned = content.replace(/```json\n?|\n?```/g, '').trim();
      return JSON.parse(cleaned);
    } catch (e) {
      console.error('Skill extraction error:', e);
      return [];
    }
  }

  /**
   * Match task requirements to worker skills
   */
  async matchTaskToWorker(taskDescription, taskCategory, workerSkills) {
    const prompt = `Given a task and worker's skills, calculate match quality.

TASK:
Category: ${taskCategory}
Description: ${taskDescription}

WORKER SKILLS:
${JSON.stringify(workerSkills, null, 2)}

Return ONLY valid JSON:
{
  "match_score": 75,
  "matching_skills": [
    {"skill": "skill name", "relevance": "high|medium|low", "reason": "why relevant"}
  ],
  "missing_skills": ["skill that would help"],
  "recommendation": "brief assessment",
  "can_complete": true
}

Consider:
- Direct skill matches (exact or synonym)
- Transferable skills
- Verification level of matching skills (higher confidence = better)
- Missing critical skills vs nice-to-haves`;

    const response = await this.ai.chat.completions.create({
      model: 'deepseek-chat',
      messages: [{ role: 'user', content: prompt }],
      max_tokens: 800,
      temperature: 0.2
    });

    try {
      const content = response.choices[0].message.content;
      const cleaned = content.replace(/```json\n?|\n?```/g, '').trim();
      return JSON.parse(cleaned);
    } catch (e) {
      return { match_score: 50, matching_skills: [], can_complete: true };
    }
  }
}

// Trust score calculation utilities
const TrustCalculator = {
  PLATFORM_WEIGHTS: {
    linkedin: 40,
    upwork: 35,
    fiverr: 35,
    freelancer: 30,
    cv: 25,
    portfolio: 15
  },

  TIER_THRESHOLDS: {
    expert: 86,
    trusted: 61,
    verified: 31,
    basic: 0
  },

  /**
   * Calculate overall trust score for a worker
   */
  calculate(worker, verifications = [], performanceStats = {}) {
    const weights = {
      platform_performance: 0.40,
      external_verification: 0.35,
      profile_completeness: 0.15,
      account_age: 0.10
    };

    let scores = {};

    // 1. Platform performance (tasks completed on Loopuman)
    if (performanceStats.tasks_completed > 0) {
      const ratingScore = ((performanceStats.avg_rating || 3) / 5) * 100;
      const completionRate = performanceStats.completion_rate || 0.8;
      scores.platform_performance = ratingScore * completionRate;
    } else {
      scores.platform_performance = 50; // Neutral for new workers
    }

    // 2. External verification score
    scores.external_verification = this.calculateVerificationScore(verifications);

    // 3. Profile completeness
    scores.profile_completeness = this.calculateProfileCompleteness(worker);

    // 4. Account age (up to 6 months)
    const monthsOld = Math.min(6, this.monthsSince(worker.created_at));
    scores.account_age = (monthsOld / 6) * 100;

    // Weighted total
    const total = Object.entries(weights).reduce((sum, [key, weight]) => {
      return sum + ((scores[key] || 0) * weight);
    }, 0);

    return {
      overall: Math.round(total),
      breakdown: scores,
      tier: this.getTier(total)
    };
  },

  calculateVerificationScore(verifications) {
    if (!verifications?.length) return 0;

    let score = 0;
    const verifiedPlatforms = new Set();

    for (const v of verifications) {
      if (v.verification_status !== 'verified') continue;
      if (verifiedPlatforms.has(v.platform)) continue; // Don't double-count

      let platformScore = this.PLATFORM_WEIGHTS[v.platform] || 10;

      // Boost based on external metrics
      if (v.external_rating >= 4.8) platformScore *= 1.25;
      else if (v.external_rating >= 4.5) platformScore *= 1.15;

      if (v.external_jobs_completed > 100) platformScore *= 1.15;
      else if (v.external_jobs_completed > 50) platformScore *= 1.1;

      score += platformScore;
      verifiedPlatforms.add(v.platform);
    }

    return Math.min(100, score);
  },

  calculateProfileCompleteness(worker) {
    let score = 0;
    const checks = [
      { field: 'name', points: 15 },
      { field: 'country', points: 15 },
      { field: 'skills', points: 30, isArray: true },
      { field: 'bio', points: 20 },
      { field: 'profile_photo', points: 20 }
    ];

    for (const check of checks) {
      if (check.isArray) {
        if (worker[check.field]?.length > 0) score += check.points;
      } else {
        if (worker[check.field]) score += check.points;
      }
    }

    return score;
  },

  getTier(score) {
    if (score >= this.TIER_THRESHOLDS.expert) return 'expert';
    if (score >= this.TIER_THRESHOLDS.trusted) return 'trusted';
    if (score >= this.TIER_THRESHOLDS.verified) return 'verified';
    return 'basic';
  },

  monthsSince(date) {
    if (!date) return 0;
    const now = new Date();
    const created = new Date(date);
    return Math.floor((now - created) / (30 * 24 * 60 * 60 * 1000));
  }
};

// Task access control based on trust tier
const TaskAccessControl = {
  RULES: {
    basic: {
      max_budget_per_task: 200,      // 200 VAE = $2
      max_concurrent_tasks: 2,
      allowed_categories: ['survey', 'data_entry', 'labeling', 'simple'],
      daily_task_limit: 10,
      payout_delay_hours: 24
    },
    verified: {
      max_budget_per_task: 500,
      max_concurrent_tasks: 5,
      allowed_categories: ['survey', 'data_entry', 'labeling', 'content', 'research', 'transcription'],
      daily_task_limit: 25,
      payout_delay_hours: 12
    },
    trusted: {
      max_budget_per_task: 2000,
      max_concurrent_tasks: 10,
      allowed_categories: 'all',
      daily_task_limit: 50,
      payout_delay_hours: 1
    },
    expert: {
      max_budget_per_task: null,     // No limit
      max_concurrent_tasks: 20,
      allowed_categories: 'all',
      daily_task_limit: null,
      payout_delay_hours: 0,
      priority_matching: true
    }
  },

  canAccess(worker, task) {
    const rules = this.RULES[worker.trust_tier || 'basic'];

    // Check budget limit
    if (rules.max_budget_per_task && task.budget > rules.max_budget_per_task) {
      return {
        allowed: false,
        reason: `Tasks over ${rules.max_budget_per_task} VAE require ${this.nextTier(worker.trust_tier)} tier or higher`
      };
    }

    // Check category
    if (rules.allowed_categories !== 'all') {
      if (!rules.allowed_categories.includes(task.category)) {
        return {
          allowed: false,
          reason: `"${task.category}" tasks require higher trust tier`
        };
      }
    }

    // Check concurrent tasks (would need worker.active_tasks)
    if (worker.active_tasks >= rules.max_concurrent_tasks) {
      return {
        allowed: false,
        reason: `You've reached the limit of ${rules.max_concurrent_tasks} concurrent tasks`
      };
    }

    return { allowed: true };
  },

  nextTier(current) {
    const order = ['basic', 'verified', 'trusted', 'expert'];
    const idx = order.indexOf(current);
    return idx < order.length - 1 ? order[idx + 1] : null;
  },

  getPayoutDelay(tier) {
    return this.RULES[tier]?.payout_delay_hours || 24;
  }
};
// ═══════════════════════════════════════════════════════════════════════════════════════
// DYNAMIC TRUST POINT CALCULATORS (based on extracted profile data)
// ═══════════════════════════════════════════════════════════════════════════════════════

/**
 * Calculate trust points from Upwork profile data
 * JSS 95%+ & $10K+ = +60, JSS 90%+ & $1K+ = +45, JSS 80%+ = +25, verified = +10
 */
function calculateUpworkTrustPoints(metrics) {
  if (!metrics || !metrics.success_rate) return { points: 10, reason: 'Upwork profile verified' };
  
  const jss = metrics.success_rate || 0;
  const earned = parseFloat(String(metrics.total_earned || '0').replace(/[$,+K]/gi, '')) || 0;
  const earnedNormalized = String(metrics.total_earned || '').includes('K') ? earned * 1000 : earned;
  
  let points = 10; // Base for verified profile
  let reason = 'Upwork verified';
  
  if (jss >= 95 && earnedNormalized >= 10000) {
    points = 60;
    reason = `Top Upwork seller: ${jss}% JSS, $${earnedNormalized.toLocaleString()}+ earned`;
  } else if (jss >= 90 && earnedNormalized >= 1000) {
    points = 45;
    reason = `Strong Upwork profile: ${jss}% JSS, $${earnedNormalized.toLocaleString()}+ earned`;
  } else if (jss >= 80) {
    points = 25;
    reason = `Good Upwork profile: ${jss}% JSS`;
  }
  
  // Bonus for Top Rated badge
  if (metrics.level && metrics.level.toLowerCase().includes('top rated')) {
    points = Math.max(points, 50);
    reason += ' (Top Rated)';
  }
  
  console.log(`[TrustCalc] Upwork: JSS=${jss}%, earned=${earnedNormalized}, points=${points}`);
  return { points, reason, metrics: { jss, earned: earnedNormalized, level: metrics.level } };
}

/**
 * Calculate trust points from Fiverr profile data
 * Top Rated = +60, Level 2 + 4.8+ = +45, Level 1 + 4.5+ = +25, verified = +10
 */
function calculateFiverrTrustPoints(metrics) {
  if (!metrics) return { points: 10, reason: 'Fiverr profile verified' };
  
  const rating = parseFloat(metrics.rating) || 0;
  const reviews = parseInt(metrics.reviews_count) || 0;
  const level = String(metrics.level || '').toLowerCase();
  
  let points = 10;
  let reason = 'Fiverr verified';
  
  if (level.includes('top rated') || level.includes('top seller')) {
    points = 60;
    reason = `Fiverr Top Rated: ${rating}⭐ (${reviews} reviews)`;
  } else if (level.includes('level 2') && rating >= 4.8) {
    points = 45;
    reason = `Fiverr Level 2: ${rating}⭐ (${reviews} reviews)`;
  } else if ((level.includes('level 1') || level.includes('level 2')) && rating >= 4.5) {
    points = 25;
    reason = `Fiverr ${level}: ${rating}⭐`;
  } else if (rating >= 4.5 && reviews >= 10) {
    points = 20;
    reason = `Fiverr seller: ${rating}⭐ (${reviews} reviews)`;
  }
  
  console.log(`[TrustCalc] Fiverr: level=${level}, rating=${rating}, reviews=${reviews}, points=${points}`);
  return { points, reason, metrics: { rating, reviews, level } };
}

/**
 * Calculate trust points from LinkedIn profile data
 * Photo match + 500+ connections = +40, photo match + active = +30, profile only = +15
 */
function calculateLinkedInTrustPoints(profileData, photoMatch = false) {
  if (!profileData) return { points: 15, reason: 'LinkedIn profile verified' };
  
  const connections = String(profileData.connections || '0').replace(/[+,]/g, '');
  const connCount = connections.includes('500') ? 500 : parseInt(connections) || 0;
  const hasPhoto = profileData.profile_photo_visible;
  const hasExperience = profileData.experience && profileData.experience.length > 0;
  
  let points = 15;
  let reason = 'LinkedIn profile verified';
  
  if (photoMatch && connCount >= 500) {
    points = 40;
    reason = `LinkedIn verified: photo match, ${connCount}+ connections`;
  } else if (photoMatch && hasExperience) {
    points = 30;
    reason = 'LinkedIn verified: photo match, active profile';
  } else if (hasPhoto && connCount >= 100) {
    points = 20;
    reason = `LinkedIn profile: ${connCount}+ connections`;
  }
  
  console.log(`[TrustCalc] LinkedIn: connections=${connCount}, photoMatch=${photoMatch}, points=${points}`);
  return { points, reason, metrics: { connections: connCount, photoMatch, hasExperience } };
}

/**
 * Get best professional verification points (only highest counts)
 */
function getBestProfessionalPoints(verifications) {
  let best = { points: 0, source: null, reason: '' };
  
  for (const v of verifications) {
    if (v.points > best.points) {
      best = { points: v.points, source: v.source, reason: v.reason };
    }
  }
  
  return best;
}
// ═══════════════════════════════════════════════════════════════════════════════════════
// DYNAMIC TRUST POINT CALCULATORS (based on extracted profile data)
// ═══════════════════════════════════════════════════════════════════════════════════════

/**
 * Calculate trust points from Upwork profile data
 * JSS 95%+ & $10K+ = +60, JSS 90%+ & $1K+ = +45, JSS 80%+ = +25, verified = +10
 */
function calculateUpworkTrustPoints(metrics) {
  if (!metrics || !metrics.success_rate) return { points: 10, reason: 'Upwork profile verified' };
  
  const jss = metrics.success_rate || 0;
  const earned = parseFloat(String(metrics.total_earned || '0').replace(/[$,+K]/gi, '')) || 0;
  const earnedNormalized = String(metrics.total_earned || '').includes('K') ? earned * 1000 : earned;
  
  let points = 10; // Base for verified profile
  let reason = 'Upwork verified';
  
  if (jss >= 95 && earnedNormalized >= 10000) {
    points = 60;
    reason = `Top Upwork seller: ${jss}% JSS, $${earnedNormalized.toLocaleString()}+ earned`;
  } else if (jss >= 90 && earnedNormalized >= 1000) {
    points = 45;
    reason = `Strong Upwork profile: ${jss}% JSS, $${earnedNormalized.toLocaleString()}+ earned`;
  } else if (jss >= 80) {
    points = 25;
    reason = `Good Upwork profile: ${jss}% JSS`;
  }
  
  // Bonus for Top Rated badge
  if (metrics.level && metrics.level.toLowerCase().includes('top rated')) {
    points = Math.max(points, 50);
    reason += ' (Top Rated)';
  }
  
  console.log(`[TrustCalc] Upwork: JSS=${jss}%, earned=${earnedNormalized}, points=${points}`);
  return { points, reason, metrics: { jss, earned: earnedNormalized, level: metrics.level } };
}

/**
 * Calculate trust points from Fiverr profile data
 * Top Rated = +60, Level 2 + 4.8+ = +45, Level 1 + 4.5+ = +25, verified = +10
 */
function calculateFiverrTrustPoints(metrics) {
  if (!metrics) return { points: 10, reason: 'Fiverr profile verified' };
  
  const rating = parseFloat(metrics.rating) || 0;
  const reviews = parseInt(metrics.reviews_count) || 0;
  const level = String(metrics.level || '').toLowerCase();
  
  let points = 10;
  let reason = 'Fiverr verified';
  
  if (level.includes('top rated') || level.includes('top seller')) {
    points = 60;
    reason = `Fiverr Top Rated: ${rating}⭐ (${reviews} reviews)`;
  } else if (level.includes('level 2') && rating >= 4.8) {
    points = 45;
    reason = `Fiverr Level 2: ${rating}⭐ (${reviews} reviews)`;
  } else if ((level.includes('level 1') || level.includes('level 2')) && rating >= 4.5) {
    points = 25;
    reason = `Fiverr ${level}: ${rating}⭐`;
  } else if (rating >= 4.5 && reviews >= 10) {
    points = 20;
    reason = `Fiverr seller: ${rating}⭐ (${reviews} reviews)`;
  }
  
  console.log(`[TrustCalc] Fiverr: level=${level}, rating=${rating}, reviews=${reviews}, points=${points}`);
  return { points, reason, metrics: { rating, reviews, level } };
}

/**
 * Calculate trust points from LinkedIn profile data
 * Photo match + 500+ connections = +40, photo match + active = +30, profile only = +15
 */
function calculateLinkedInTrustPoints(profileData, photoMatch = false) {
  if (!profileData) return { points: 15, reason: 'LinkedIn profile verified' };
  
  const connections = String(profileData.connections || '0').replace(/[+,]/g, '');
  const connCount = connections.includes('500') ? 500 : parseInt(connections) || 0;
  const hasPhoto = profileData.profile_photo_visible;
  const hasExperience = profileData.experience && profileData.experience.length > 0;
  
  let points = 15;
  let reason = 'LinkedIn profile verified';
  
  if (photoMatch && connCount >= 500) {
    points = 40;
    reason = `LinkedIn verified: photo match, ${connCount}+ connections`;
  } else if (photoMatch && hasExperience) {
    points = 30;
    reason = 'LinkedIn verified: photo match, active profile';
  } else if (hasPhoto && connCount >= 100) {
    points = 20;
    reason = `LinkedIn profile: ${connCount}+ connections`;
  }
  
  console.log(`[TrustCalc] LinkedIn: connections=${connCount}, photoMatch=${photoMatch}, points=${points}`);
  return { points, reason, metrics: { connections: connCount, photoMatch, hasExperience } };
}

/**
 * Get best professional verification points (only highest counts)
 */
function getBestProfessionalPoints(verifications) {
  let best = { points: 0, source: null, reason: '' };
  
  for (const v of verifications) {
    if (v.points > best.points) {
      best = { points: v.points, source: v.source, reason: v.reason };
    }
  }
  
  return best;
}
// ═══════════════════════════════════════════════════════════════════════════════════════
// DYNAMIC TRUST POINT CALCULATORS (based on extracted profile data)
// ═══════════════════════════════════════════════════════════════════════════════════════

/**
 * Calculate trust points from Upwork profile data
 * JSS 95%+ & $10K+ = +60, JSS 90%+ & $1K+ = +45, JSS 80%+ = +25, verified = +10
 */
function calculateUpworkTrustPoints(metrics) {
  if (!metrics || !metrics.success_rate) return { points: 10, reason: 'Upwork profile verified' };
  
  const jss = metrics.success_rate || 0;
  const earned = parseFloat(String(metrics.total_earned || '0').replace(/[$,+K]/gi, '')) || 0;
  const earnedNormalized = String(metrics.total_earned || '').includes('K') ? earned * 1000 : earned;
  
  let points = 10; // Base for verified profile
  let reason = 'Upwork verified';
  
  if (jss >= 95 && earnedNormalized >= 10000) {
    points = 60;
    reason = `Top Upwork seller: ${jss}% JSS, $${earnedNormalized.toLocaleString()}+ earned`;
  } else if (jss >= 90 && earnedNormalized >= 1000) {
    points = 45;
    reason = `Strong Upwork profile: ${jss}% JSS, $${earnedNormalized.toLocaleString()}+ earned`;
  } else if (jss >= 80) {
    points = 25;
    reason = `Good Upwork profile: ${jss}% JSS`;
  }
  
  // Bonus for Top Rated badge
  if (metrics.level && metrics.level.toLowerCase().includes('top rated')) {
    points = Math.max(points, 50);
    reason += ' (Top Rated)';
  }
  
  console.log(`[TrustCalc] Upwork: JSS=${jss}%, earned=${earnedNormalized}, points=${points}`);
  return { points, reason, metrics: { jss, earned: earnedNormalized, level: metrics.level } };
}

/**
 * Calculate trust points from Fiverr profile data
 * Top Rated = +60, Level 2 + 4.8+ = +45, Level 1 + 4.5+ = +25, verified = +10
 */
function calculateFiverrTrustPoints(metrics) {
  if (!metrics) return { points: 10, reason: 'Fiverr profile verified' };
  
  const rating = parseFloat(metrics.rating) || 0;
  const reviews = parseInt(metrics.reviews_count) || 0;
  const level = String(metrics.level || '').toLowerCase();
  
  let points = 10;
  let reason = 'Fiverr verified';
  
  if (level.includes('top rated') || level.includes('top seller')) {
    points = 60;
    reason = `Fiverr Top Rated: ${rating}⭐ (${reviews} reviews)`;
  } else if (level.includes('level 2') && rating >= 4.8) {
    points = 45;
    reason = `Fiverr Level 2: ${rating}⭐ (${reviews} reviews)`;
  } else if ((level.includes('level 1') || level.includes('level 2')) && rating >= 4.5) {
    points = 25;
    reason = `Fiverr ${level}: ${rating}⭐`;
  } else if (rating >= 4.5 && reviews >= 10) {
    points = 20;
    reason = `Fiverr seller: ${rating}⭐ (${reviews} reviews)`;
  }
  
  console.log(`[TrustCalc] Fiverr: level=${level}, rating=${rating}, reviews=${reviews}, points=${points}`);
  return { points, reason, metrics: { rating, reviews, level } };
}

/**
 * Calculate trust points from LinkedIn profile data
 * Photo match + 500+ connections = +40, photo match + active = +30, profile only = +15
 */
function calculateLinkedInTrustPoints(profileData, photoMatch = false) {
  if (!profileData) return { points: 15, reason: 'LinkedIn profile verified' };
  
  const connections = String(profileData.connections || '0').replace(/[+,]/g, '');
  const connCount = connections.includes('500') ? 500 : parseInt(connections) || 0;
  const hasPhoto = profileData.profile_photo_visible;
  const hasExperience = profileData.experience && profileData.experience.length > 0;
  
  let points = 15;
  let reason = 'LinkedIn profile verified';
  
  if (photoMatch && connCount >= 500) {
    points = 40;
    reason = `LinkedIn verified: photo match, ${connCount}+ connections`;
  } else if (photoMatch && hasExperience) {
    points = 30;
    reason = 'LinkedIn verified: photo match, active profile';
  } else if (hasPhoto && connCount >= 100) {
    points = 20;
    reason = `LinkedIn profile: ${connCount}+ connections`;
  }
  
  console.log(`[TrustCalc] LinkedIn: connections=${connCount}, photoMatch=${photoMatch}, points=${points}`);
  return { points, reason, metrics: { connections: connCount, photoMatch, hasExperience } };
}

/**
 * Get best professional verification points (only highest counts)
 */
function getBestProfessionalPoints(verifications) {
  let best = { points: 0, source: null, reason: '' };
  
  for (const v of verifications) {
    if (v.points > best.points) {
      best = { points: v.points, source: v.source, reason: v.reason };
    }
  }
  
  return best;
}

// ═══════════════════════════════════════════════════════════════════════════════════════
// DYNAMIC TRUST POINT CALCULATORS (based on extracted profile data)
// ═══════════════════════════════════════════════════════════════════════════════════════

function calculateUpworkTrustPoints(metrics) {
  if (!metrics || !metrics.success_rate) return { points: 10, reason: 'Upwork profile verified' };
  const jss = metrics.success_rate || 0;
  const earned = parseFloat(String(metrics.total_earned || '0').replace(/[$,+K]/gi, '')) || 0;
  const earnedNormalized = String(metrics.total_earned || '').includes('K') ? earned * 1000 : earned;
  let points = 10, reason = 'Upwork verified';
  if (jss >= 95 && earnedNormalized >= 10000) { points = 60; reason = `Top Upwork: ${jss}% JSS, $${earnedNormalized}+ earned`; }
  else if (jss >= 90 && earnedNormalized >= 1000) { points = 45; reason = `Strong Upwork: ${jss}% JSS`; }
  else if (jss >= 80) { points = 25; reason = `Good Upwork: ${jss}% JSS`; }
  if (metrics.level && metrics.level.toLowerCase().includes('top rated')) { points = Math.max(points, 50); }
  console.log('[TrustCalc] Upwork: JSS=' + jss + ', points=' + points);
  return { points, reason, metrics: { jss, earned: earnedNormalized, level: metrics.level } };
}

function calculateFiverrTrustPoints(metrics) {
  if (!metrics) return { points: 10, reason: 'Fiverr profile verified' };
  const rating = parseFloat(metrics.rating) || 0;
  const reviews = parseInt(metrics.reviews_count) || 0;
  const level = String(metrics.level || '').toLowerCase();
  let points = 10, reason = 'Fiverr verified';
  if (level.includes('top rated')) { points = 60; reason = `Fiverr Top Rated: ${rating}★`; }
  else if (level.includes('level 2') && rating >= 4.8) { points = 45; reason = `Fiverr Level 2: ${rating}★`; }
  else if (level.includes('level 1') && rating >= 4.5) { points = 25; reason = `Fiverr Level 1: ${rating}★`; }
  console.log('[TrustCalc] Fiverr: level=' + level + ', rating=' + rating + ', points=' + points);
  return { points, reason, metrics: { rating, reviews, level } };
}

function calculateLinkedInTrustPoints(profileData, photoMatch) {
  if (!profileData) return { points: 15, reason: 'LinkedIn profile verified' };
  const connStr = String(profileData.connections || '0').replace(/[+,]/g, '');
  const connCount = connStr.includes('500') ? 500 : parseInt(connStr) || 0;
  let points = 15, reason = 'LinkedIn verified';
  if (photoMatch && connCount >= 500) { points = 40; reason = 'LinkedIn: photo match, 500+ connections'; }
  else if (photoMatch) { points = 30; reason = 'LinkedIn: photo match'; }
  else if (connCount >= 100) { points = 20; reason = 'LinkedIn: ' + connCount + '+ connections'; }
  console.log('[TrustCalc] LinkedIn: connections=' + connCount + ', points=' + points);
  return { points, reason, metrics: { connections: connCount, photoMatch } };
}

function getBestProfessionalPoints(verifications) {
  let best = { points: 0, source: null, reason: '' };
  for (const v of verifications) { if (v.points > best.points) best = v; }
  return best;
}


// ═══════════════════════════════════════════════════════════════════════════════════════
// DYNAMIC TRUST POINT CALCULATORS (based on extracted profile data)
// ═══════════════════════════════════════════════════════════════════════════════════════

function calculateUpworkTrustPoints(metrics) {
  if (!metrics || !metrics.success_rate) return { points: 10, reason: 'Upwork profile verified' };
  const jss = metrics.success_rate || 0;
  const earned = parseFloat(String(metrics.total_earned || '0').replace(/[$,+K]/gi, '')) || 0;
  const earnedNormalized = String(metrics.total_earned || '').includes('K') ? earned * 1000 : earned;
  let points = 10, reason = 'Upwork verified';
  if (jss >= 95 && earnedNormalized >= 10000) { points = 60; reason = `Top Upwork: ${jss}% JSS, $${earnedNormalized}+ earned`; }
  else if (jss >= 90 && earnedNormalized >= 1000) { points = 45; reason = `Strong Upwork: ${jss}% JSS`; }
  else if (jss >= 80) { points = 25; reason = `Good Upwork: ${jss}% JSS`; }
  if (metrics.level && metrics.level.toLowerCase().includes('top rated')) { points = Math.max(points, 50); }
  console.log('[TrustCalc] Upwork: JSS=' + jss + ', points=' + points);
  return { points, reason, metrics: { jss, earned: earnedNormalized, level: metrics.level } };
}

function calculateFiverrTrustPoints(metrics) {
  if (!metrics) return { points: 10, reason: 'Fiverr profile verified' };
  const rating = parseFloat(metrics.rating) || 0;
  const reviews = parseInt(metrics.reviews_count) || 0;
  const level = String(metrics.level || '').toLowerCase();
  let points = 10, reason = 'Fiverr verified';
  if (level.includes('top rated')) { points = 60; reason = `Fiverr Top Rated: ${rating}★`; }
  else if (level.includes('level 2') && rating >= 4.8) { points = 45; reason = `Fiverr Level 2: ${rating}★`; }
  else if (level.includes('level 1') && rating >= 4.5) { points = 25; reason = `Fiverr Level 1: ${rating}★`; }
  console.log('[TrustCalc] Fiverr: level=' + level + ', rating=' + rating + ', points=' + points);
  return { points, reason, metrics: { rating, reviews, level } };
}

function calculateLinkedInTrustPoints(profileData, photoMatch) {
  if (!profileData) return { points: 15, reason: 'LinkedIn profile verified' };
  const connStr = String(profileData.connections || '0').replace(/[+,]/g, '');
  const connCount = connStr.includes('500') ? 500 : parseInt(connStr) || 0;
  let points = 15, reason = 'LinkedIn verified';
  if (photoMatch && connCount >= 500) { points = 40; reason = 'LinkedIn: photo match, 500+ connections'; }
  else if (photoMatch) { points = 30; reason = 'LinkedIn: photo match'; }
  else if (connCount >= 100) { points = 20; reason = 'LinkedIn: ' + connCount + '+ connections'; }
  console.log('[TrustCalc] LinkedIn: connections=' + connCount + ', points=' + points);
  return { points, reason, metrics: { connections: connCount, photoMatch } };
}

function getBestProfessionalPoints(verifications) {
  let best = { points: 0, source: null, reason: '' };
  for (const v of verifications) { if (v.points > best.points) best = v; }
  return best;
}


module.exports = {
  AIVerificationEngine,
  TrustCalculator,
  TaskAccessControl,
  calculateUpworkTrustPoints,
  calculateFiverrTrustPoints,
  calculateLinkedInTrustPoints,
  getBestProfessionalPoints
};
