// PRE Web GUI — Integration management routes (delegates, MCP config, hooks, argus)
const { Router } = require('express');
const delegate = require('../tools/delegate');
const mcp = require('../mcp');
const hooksSystem = require('../hooks');
const argusSystem = require('../argus');

// Factory: broadcastWS is needed for argus reply broadcast
module.exports = function createIntegrationRoutes(broadcastWS) {
  const router = Router();

  // ── Delegates (frontier AI) ──

  router.get('/delegates', (_req, res) => {
    res.json(delegate.checkAvailability());
  });

  // ── MCP (Model Context Protocol) config ──

  router.get('/mcp', (_req, res) => {
    res.json(mcp.getStatus());
  });

  router.post('/mcp/connect', async (req, res) => {
    const { name } = req.body;
    if (!name) return res.status(400).json({ error: 'name required' });
    const config = mcp.loadConfig();
    const serverConfig = config.servers?.[name];
    if (!serverConfig) return res.status(404).json({ error: `Server '${name}' not configured` });
    try {
      await mcp.connectServer(name, serverConfig);
      res.json({ connected: true, tools: mcp.getStatus()[name]?.tools || 0 });
    } catch (err) {
      res.status(500).json({ error: err.message });
    }
  });

  router.post('/mcp/disconnect', async (req, res) => {
    const { name } = req.body;
    if (!name) return res.status(400).json({ error: 'name required' });
    await mcp.disconnectServer(name);
    res.json({ disconnected: true });
  });

  router.post('/mcp/add', async (req, res) => {
    const { name, command, args, env, url } = req.body;
    if (!name) return res.status(400).json({ error: 'name required' });
    if (!command && !url) return res.status(400).json({ error: 'command or url required' });
    const serverConfig = url ? { url } : { command, args: args || [], env: env || {} };
    mcp.addServer(name, serverConfig);
    try {
      await mcp.connectServer(name, serverConfig);
      res.json({ added: true, connected: true, tools: mcp.getStatus()[name]?.tools || 0 });
    } catch (err) {
      res.json({ added: true, connected: false, error: err.message });
    }
  });

  router.delete('/mcp/:name', async (req, res) => {
    await mcp.removeServer(req.params.name);
    res.json({ removed: true });
  });

  // ── Hooks ──

  router.get('/hooks', (_req, res) => {
    res.json(hooksSystem.listHooks());
  });

  router.post('/hooks', (req, res) => {
    const result = hooksSystem.addHook(req.body || {});
    if (result.error) return res.status(400).json({ error: result.error });
    res.json(result);
  });

  router.patch('/hooks/:id/toggle', (req, res) => {
    const result = hooksSystem.toggleHook(req.params.id);
    if (result.error) return res.status(404).json({ error: result.error });
    res.json(result);
  });

  router.delete('/hooks/:id', (req, res) => {
    const result = hooksSystem.removeHook(req.params.id);
    if (result.error) return res.status(404).json({ error: result.error });
    res.json(result);
  });

  // ── Argus companion ──

  router.get('/argus', (_req, res) => {
    res.json(argusSystem.getConfig());
  });

  router.post('/argus', (req, res) => {
    res.json(argusSystem.saveConfig(req.body));
  });

  router.get('/argus/status', (_req, res) => {
    res.json(argusSystem.getStatus());
  });

  router.post('/argus/reply', async (req, res) => {
    const { reactionId, reply } = req.body;
    if (!reactionId || !reply) return res.status(400).json({ error: 'reactionId and reply are required' });
    const result = await argusSystem.replyToReaction(reactionId, reply);
    if (result.error) return res.status(404).json(result);
    broadcastWS({ type: 'argus_reply', ...result, name: argusSystem.getConfig().name, timestamp: Date.now() });
    res.json(result);
  });

  return router;
};
