const fs = require("fs");
const express = require("express");
const bodyParser = require("body-parser");

const app = express();

app.use(bodyParser.json({ limit: "50mb" }));
app.use(bodyParser.urlencoded({ limit: "50mb", extended: false }));

// Server listening to PORT 3002

// Add these state variables at the top
let agentsReady = 0;
let activeConversation = false;
let agentInfo = {};
let currentTask = null;
let latestConversation = "";
// Add these new endpoints
app.post("/ready-for-communication", (req, res) => {
    const { agent, task, info } = req.body;
    agentsReady += 1;
    agentInfo[agent] = info;
    if (agent === "weak") {
        currentTask = task;
    }

    if (agentsReady === 2) {
        activeConversation = true;
        agentsReady = 0;
    }

    res.json({ success: true });
});

app.get("/conversation", (req, res) => {
    res.json({
        active: activeConversation,
        agents: agentsReady,
        task: currentTask,
    });
});

app.post("/latest-conversation", (req, res) => {
    const { conversation } = req.body;
    latestConversation = conversation;
    res.json({ success: true });
});

app.get("/latest-conversation", (req, res) => {
    res.json({
        conversation: latestConversation,
    });
});

app.get("/agent-info", (req, res) => {
    console.log(agentInfo);
    const { agent } = req.body;
    console.log(agentInfo[agent]);
    res.json(agentInfo[agent] || {});
});

app.post("/finish-conversation", (req, res) => {
    activeConversation = false;
    agentInfo = {};
    currentTask = null;
    res.json({ success: true });
});

const DEFAULT_PORT = 3002;
const PORT = process.argv[2] || DEFAULT_PORT;
app.listen(PORT, () => {
    console.log(`Server started on port ${PORT}`);
});
