function registerAgentRoutes(app, { agents, briefing }) {
  app.get('/api/agents', (req, res) => {
    const divisionId = parseInt(req.query.division_id, 10);
    if (!divisionId) return res.status(400).json({ error: 'division_id query required' });
    res.json({ agents: agents.listAgentsForDivision(divisionId) });
  });

  app.get('/api/agent-runs', (req, res) => {
    const divisionId = parseInt(req.query.division_id, 10);
    if (!divisionId) return res.status(400).json({ error: 'division_id query required' });
    res.json({ runs: agents.getRunsForDivision(divisionId) });
  });

  app.post('/api/agents/generate', async (req, res) => {
    try {
      const agent = await agents.generateAgentSpec(req.body || {});
      res.json({ success: true, agent });
    } catch (error) {
      res.status(400).json({ error: error.message });
    }
  });

  app.put('/api/agents/:id', (req, res) => {
    try {
      const agent = agents.updateAgent(parseInt(req.params.id, 10), parseInt(req.body?.requested_by_division_id, 10), req.body || {});
      res.json({ success: true, agent });
    } catch (error) {
      res.status(400).json({ error: error.message });
    }
  });

  app.delete('/api/agents/:id', (req, res) => {
    try {
      const result = agents.deleteAgent(parseInt(req.params.id, 10), parseInt(req.body?.requested_by_division_id || req.query.requested_by_division_id, 10));
      res.json(result);
    } catch (error) {
      res.status(400).json({ error: error.message });
    }
  });

  app.post('/api/agents/:id/run', async (req, res) => {
    try {
      const result = await agents.runAgent(parseInt(req.params.id, 10), parseInt(req.body?.division_id, 10) || null, 'manual');
      briefing.invalidateBriefingCache();
      res.json({ success: true, ...result });
    } catch (error) {
      res.status(400).json({ error: error.message });
    }
  });

  app.post('/api/agents/run', async (req, res) => {
    try {
      const divisionId = parseInt(req.body?.division_id, 10) || 8;
      const results = await agents.runAgentsForDivision(divisionId, { includeScheduled: true, triggerMode: 'manual' });
      briefing.invalidateBriefingCache();
      res.json({
        success: true,
        actions: results.map((result) => `${result.agent.name}: ${result.summary}`),
        results
      });
    } catch (error) {
      res.status(400).json({ error: error.message });
    }
  });
}

module.exports = { registerAgentRoutes };
