// Insert rename + download API endpoints after the mkdir endpoint
const fs = require('fs');
const f  = 'E:/Deployment/routes/api.js';
let src  = fs.readFileSync(f, 'utf8').replace(/\r\n/g, '\n');

const anchor = '\n// \u2500\u2500\u2500 Activity Log';
const idx = src.indexOf(anchor);
if (idx === -1) { console.error('Anchor not found!'); process.exit(1); }

const NEW_ENDPOINTS = `
// Rename file or folder
router.put('/files/:siteId/rename', (req, res) => {
  const site = findSite(req.params.siteId);
  if (!site) return res.status(404).json({ error: 'Site not found' });
  const { from, to } = req.body;
  if (!from || !to) return res.status(400).json({ error: 'from and to are required' });
  let srcPath, destPath;
  try { srcPath = safePath(site.deployPath, from); destPath = safePath(site.deployPath, to); }
  catch (e) { return res.status(e.status || 400).json({ error: e.message }); }
  if (!fs.existsSync(srcPath)) return res.status(404).json({ error: 'Source not found' });
  if (fs.existsSync(destPath)) return res.status(409).json({ error: 'A file with that name already exists' });
  try {
    fs.renameSync(srcPath, destPath);
    log.info('filemanager', \`Renamed \${from} \u2192 \${to}\`);
    res.json({ ok: true });
  } catch (err) { res.status(500).json({ error: err.message }); }
});

// Download a single file
router.get('/files/:siteId/download', (req, res) => {
  const site = findSite(req.params.siteId);
  if (!site) return res.status(404).json({ error: 'Site not found' });
  let target;
  try { target = safePath(site.deployPath, req.query.path || ''); }
  catch (e) { return res.status(e.status || 400).json({ error: e.message }); }
  if (!fs.existsSync(target) || fs.statSync(target).isDirectory())
    return res.status(404).json({ error: 'File not found' });
  const filename = path.basename(target);
  res.setHeader('Content-Disposition', \`attachment; filename="\${filename}"\`);
  res.setHeader('Content-Type', 'application/octet-stream');
  fs.createReadStream(target).pipe(res);
});

`;

src = src.slice(0, idx) + NEW_ENDPOINTS + src.slice(idx);
fs.writeFileSync(f, src.replace(/\n/g, '\r\n'), 'utf8');
console.log('Done — rename + download endpoints inserted');
