const fs = require('fs');
const file = process.env.HOME + '/loopuman-backend/telegram-bot.js';
fs.copyFileSync(file, file + '.bak-ref-fix');
console.log('Backup created');
let code = fs.readFileSync(file, 'utf8');
let changes = 0;

// EDIT 1: Browse - stop auto-sending
const OLD1 = `  if (task.reference_media?.length > 0) {
    msg += \`\\n\\n📎 <b>Reference files:</b> \${task.reference_media.length} attached\`;
  }
  
  await edit(ctx, msg, Markup.inlineKeyboard(btns));
  
  // Send reference media as separate messages to worker
  if (task.reference_media?.length > 0) {
    for (const media of task.reference_media) {
      try {
        if (media.file_id) {
          if (media.type === 'photo') {
            await ctx.telegram.sendPhoto(ctx.chat.id, media.file_id, { caption: \`📎 \${media.filename || 'Reference'}\` });
          } else {
            await ctx.telegram.sendDocument(ctx.chat.id, media.file_id, { caption: \`📎 \${media.filename || 'Reference'}\` });
          }
        } else if (media.url) {
          if (media.type === 'image') {
            await ctx.telegram.sendPhoto(ctx.chat.id, media.url, { caption: \`📎 \${media.filename || 'Reference'}\` });
          } else {
            await ctx.telegram.sendDocument(ctx.chat.id, media.url, { caption: \`📎 \${media.filename || 'Reference'}\` });
          }
        }
      } catch (e) { console.error('Ref media error:', e.message); }
    }
  }
});`;
const NEW1 = `  if (task.reference_media?.length > 0) {
    msg += \`\\n\\n📎 <b>Reference files:</b> \${task.reference_media.length} attached <i>(visible after acceptance)</i>\`;
  }
  
  await edit(ctx, msg, Markup.inlineKeyboard(btns));
});`;
if (code.includes(OLD1)) { code = code.replace(OLD1, NEW1); changes++; console.log('Edit 1: Browse view fixed'); }
else console.log('Edit 1: NOT FOUND');

// EDIT 2: After acceptance - send ref files
const OLD2 = `  msg += \`\\n<i>Submit your work when ready!</i>\`;
  
  await edit(ctx, msg, Markup.inlineKeyboard([
    [Markup.button.callback('📤 Submit Work', \`submit_\${sub.id}\`)],
    [Markup.button.callback('❓ Ask Question', \`msg_req_\${sub.id}\`)],
    [Markup.button.callback('🚫 Abandon', \`abandon_\${sub.id}\`)],
    [Markup.button.callback('💼 My Tasks', 'my_tasks')],
  ]));
  
  // Notify requester
  if (task.requester?.telegram_id) {
    notify(task.requester.telegram_id,`;
const NEW2 = `  if (task.reference_media?.length > 0) {
    msg += \`\\n📎 <b>Reference files:</b> \${task.reference_media.length} — sending below...\\n\`;
  }
  msg += \`\\n<i>Submit your work when ready!</i>\`;
  
  await edit(ctx, msg, Markup.inlineKeyboard([
    [Markup.button.callback('📤 Submit Work', \`submit_\${sub.id}\`)],
    [Markup.button.callback('❓ Ask Question', \`msg_req_\${sub.id}\`)],
    [Markup.button.callback('🚫 Abandon', \`abandon_\${sub.id}\`)],
    [Markup.button.callback('💼 My Tasks', 'my_tasks')],
  ]));
  
  // Send reference files after acceptance
  if (task.reference_media?.length > 0) {
    for (const m of task.reference_media) {
      try {
        const source = m.file_id || m.url;
        if (!source) continue;
        const caption = \`📎 \${m.filename || 'Reference'}\`;
        if (m.type === 'photo' || m.type === 'image') {
          await ctx.telegram.sendPhoto(ctx.chat.id, source, { caption });
        } else {
          await ctx.telegram.sendDocument(ctx.chat.id, source, { caption });
        }
      } catch (e) { console.error('Ref media send error:', e.message); }
    }
  }
  
  // Notify requester
  if (task.requester?.telegram_id) {
    notify(task.requester.telegram_id,`;
if (code.includes(OLD2)) { code = code.replace(OLD2, NEW2); changes++; console.log('Edit 2: Acceptance sends ref files'); }
else console.log('Edit 2: NOT FOUND');

// EDIT 3: My Tasks - add ref files button
const OLD3 = `  if (sub.status === 'in_progress') {
    btns.push([Markup.button.callback('📤 Submit Work', \`submit_\${sub.id}\`)]);
    btns.push([Markup.button.callback('❓ Ask Question', \`msg_req_\${sub.id}\`)]);
    btns.push([Markup.button.callback('🚫 Abandon', \`abandon_\${sub.id}\`)]);
  }`;
const NEW3 = `  if (sub.status === 'in_progress') {
    btns.push([Markup.button.callback('📤 Submit Work', \`submit_\${sub.id}\`)]);
    if (task.reference_media?.length > 0) {
      btns.push([Markup.button.callback(\`📎 View \${task.reference_media.length} Reference File(s)\`, \`view_ref_\${task.id}\`)]);
    }
    btns.push([Markup.button.callback('❓ Ask Question', \`msg_req_\${sub.id}\`)]);
    btns.push([Markup.button.callback('🚫 Abandon', \`abandon_\${sub.id}\`)]);
  }`;
if (code.includes(OLD3)) { code = code.replace(OLD3, NEW3); changes++; console.log('Edit 3: My Tasks ref button added'); }
else console.log('Edit 3: NOT FOUND');

// EDIT 4: Add view_ref handler
if (!code.includes('view_ref_')) {
  const marker = '// Submit work\nbot.action(/^submit_([a-f0-9-]+)$/,';
  const handler = `// View reference files on demand
bot.action(/^view_ref_([a-f0-9-]+)$/, async (ctx) => {
  await cb(ctx);
  const taskId = ctx.match[1];
  const task = await db.getTask(taskId);
  if (!task?.reference_media?.length) return ctx.answerCbQuery('No reference files');
  await ctx.answerCbQuery(\`Sending \${task.reference_media.length} file(s)...\`);
  for (const m of task.reference_media) {
    try {
      const source = m.file_id || m.url;
      if (!source) continue;
      const caption = \`📎 \${m.filename || 'Reference'} — \${fmt.esc(fmt.short(task.title, 30))}\`;
      if (m.type === 'photo' || m.type === 'image') {
        await ctx.telegram.sendPhoto(ctx.chat.id, source, { caption, parse_mode: 'HTML' });
      } else {
        await ctx.telegram.sendDocument(ctx.chat.id, source, { caption, parse_mode: 'HTML' });
      }
    } catch (e) { console.error('Ref media error:', e.message); }
  }
});

`;
  if (code.includes(marker)) { code = code.replace(marker, handler + marker); changes++; console.log('Edit 4: view_ref handler added'); }
  else console.log('Edit 4: marker NOT FOUND');
} else console.log('Edit 4: already exists');

// EDIT 5: Local acceptance - send ref files
const OLD5 = `  msg += \`📍 <b>GPS Required:</b> You must submit from \${fmt.esc(task.location)}\\n\\n\`;
  msg += \`<i>Go to My Tasks to see instructions and submit.</i>\`;
  
  await edit(ctx, msg, Markup.inlineKeyboard([
    [Markup.button.callback('📋 My Tasks', 'my_tasks')],
    [Markup.button.callback('🔙 Browse More', 'browse')],
  ]));
});`;
const NEW5 = `  msg += \`📍 <b>GPS Required:</b> You must submit from \${fmt.esc(task.location)}\\n\\n\`;
  if (task.reference_media?.length > 0) {
    msg += \`📎 <b>Reference files:</b> \${task.reference_media.length} — sending below...\\n\\n\`;
  }
  msg += \`<i>Go to My Tasks to see instructions and submit.</i>\`;
  
  await edit(ctx, msg, Markup.inlineKeyboard([
    [Markup.button.callback('📋 My Tasks', 'my_tasks')],
    [Markup.button.callback('🔙 Browse More', 'browse')],
  ]));
  
  if (task.reference_media?.length > 0) {
    for (const m of task.reference_media) {
      try {
        const source = m.file_id || m.url;
        if (!source) continue;
        const caption = \`📎 \${m.filename || 'Reference'}\`;
        if (m.type === 'photo' || m.type === 'image') {
          await ctx.telegram.sendPhoto(ctx.chat.id, source, { caption });
        } else {
          await ctx.telegram.sendDocument(ctx.chat.id, source, { caption });
        }
      } catch (e) { console.error('Ref media send error:', e.message); }
    }
  }
});`;
if (code.includes(OLD5)) { code = code.replace(OLD5, NEW5); changes++; console.log('Edit 5: Local acceptance sends ref files'); }
else console.log('Edit 5: NOT FOUND');

fs.writeFileSync(file, code);
console.log('\nApplied ' + changes + '/5 edits');
console.log('Run: node --check telegram-bot.js && pm2 restart telegram-bot');
