const fs = require('fs');
const file = 'src/server.ts';
let code = fs.readFileSync(file, 'utf8');

// Remove imports of orchestrator, atlas, etc.
code = code.replace(/import \{ orchestratorChat.*?\n/g, "");
code = code.replace(/import \{ atlasChat.*?\n/g, "");
code = code.replace(/import \{ createJob.*?\n/g, "");
code = code.replace(/import \{ runAgent \}.*?\n/g, "");
code = code.replace(/import \{ LLMMessage, createLLM \}.*?\n/g, "");
code = code.replace(/import \{ ingestSessionEvents \}.*?\n/g, "");

// Cut everything between app.get('/api/status'...) and app.post('/agent/execute'...)
const statusStart = code.indexOf("app.get('/api/status'");
const execStart = code.indexOf("app.post('/agent/execute'");

if (statusStart > -1 && execStart > -1) {
    const toKeep = code.substring(statusStart, code.indexOf("});", statusStart) + 3);
    code = code.substring(0, statusStart) + toKeep + "\n\nconst activeSessions = new Map<string, { stopped: boolean }>();\n\n" + code.substring(execStart);
}

// Cut everything between app.post('/agent/stop'...) and app.listen(...)
const stopStart = code.indexOf("app.post('/agent/stop'");
const listenStart = code.indexOf("app.listen(");

if (stopStart > -1 && listenStart > -1) {
    const toKeepStop = code.substring(stopStart, code.indexOf("});", stopStart) + 3);
    code = code.substring(0, stopStart) + toKeepStop + "\n\n" + code.substring(listenStart);
}

fs.writeFileSync(file, code);
console.log("Server.ts cleaned up.");
