const fs = require('fs');
let code = fs.readFileSync('/home/ubuntu/loopuman-backend/enterprise-api.js', 'utf8');
let fixes = 0;

// FIX 1: Async task commission
const old1 = 'const deducted = await deductBalanceAtomic(req.userId, totalBudget);';
if (code.includes(old1)) {
  code = code.replace(old1, 'const requesterCost = Math.ceil(totalBudget * 1.2);\n    const deducted = await deductBalanceAtomic(req.userId, requesterCost);');
  fixes++;
  console.log('Fix 1: Async task commission');
}

// FIX 2: Sync task commission
const old2 = 'const deducted = await deductBalanceAtomic(req.userId, budget);';
if (code.includes(old2)) {
  code = code.replace(old2, 'const requesterCost = Math.ceil(budget * 1.2);\n  const deducted = await deductBalanceAtomic(req.userId, requesterCost);');
  fixes++;
  console.log('Fix 2: Sync task commission');
}

// FIX 3: Bulk task commission
const old3 = 'const deducted = await deductBalanceAtomic(req.userId, totalCost);';
if (code.includes(old3)) {
  code = code.replace(old3, 'const requesterCost = Math.ceil(totalCost * 1.2);\n    const deducted = await deductBalanceAtomic(req.userId, requesterCost);');
  fixes++;
  console.log('Fix 3: Bulk task commission');
}

// FIX 4: Media normalization
const old4 = 'reference_media: req.body.reference_media || [],';
if (code.includes(old4)) {
  code = code.replace(old4, "reference_media: (req.body.reference_media || []).map(m => {\n          if (typeof m === 'string') {\n            const isImage = /\\\\.(jpg|jpeg|png|gif|webp|bmp)$/i.test(m);\n            return { type: isImage ? 'image' : 'document', url: m, filename: m.split('/').pop() || 'file' };\n          }\n          return m;\n        }),");
  fixes++;
  console.log('Fix 4: Media normalization');
}

// FIX 5: Estimated seconds + hourly rate floor
const budgetCheck = "if (budget < 10 || budget > 100000) {\n      return res.status(400).json({ error: 'Budget must be between";
const idx = code.indexOf(budgetCheck);
if (idx > -1) {
  const endOfBlock = code.indexOf('}', idx + budgetCheck.length) + 1;
  const insertPoint = code.indexOf('\n', endOfBlock) + 1;
  const addition = "\n    // Estimated time + minimum hourly rate enforcement\n    const estimatedSeconds = parseInt(req.body.estimated_seconds) || null;\n    if (estimatedSeconds) {\n      const hourlyRate = (budget / CONFIG.VAE_RATE) / (estimatedSeconds / 3600);\n      if (hourlyRate < 6) {\n        const minBudget = Math.ceil(6 * (estimatedSeconds / 3600) * CONFIG.VAE_RATE);\n        return res.status(400).json({\n          error: 'Task pay rate too low',\n          effective_hourly: '$' + hourlyRate.toFixed(2) + '/hr',\n          minimum_hourly: '$6.00/hr',\n          suggested_budget_vae: minBudget,\n          suggested_budget_usd: '$' + (minBudget / CONFIG.VAE_RATE).toFixed(2),\n          message: 'Loopuman enforces a $6/hr minimum effective rate to ensure fair worker pay.'\n        });\n      }\n    }\n";
  code = code.slice(0, insertPoint) + addition + code.slice(insertPoint);
  fixes++;
  console.log('Fix 5: Estimated seconds + $6/hr floor');
}

// FIX 6: Store estimated_seconds in metadata
const old6 = "metadata: { ...(metadata || {}), api_source: true, priority: priority || 'normal', auto_approve: !!auto_approve },";
if (code.includes(old6)) {
  code = code.replace(old6, "metadata: { ...(metadata || {}), api_source: true, priority: priority || 'normal', auto_approve: !!auto_approve, estimated_seconds: estimatedSeconds || null },");
  fixes++;
  console.log('Fix 6: Store estimated_seconds in metadata');
}

fs.writeFileSync('/home/ubuntu/loopuman-backend/enterprise-api.js', code);
console.log('\nTotal fixes:', fixes);
