// PRE Web GUI — Intelligence routes (agents, training, calibration, knowledge graph, telemetry)
const { Router } = require('express');

const router = Router();

// ── Background Agents ──

const bgAgents = require('../background-agents');

router.get('/agents', (_req, res) => {
  res.json({ agents: bgAgents.listAgents(), queue: bgAgents.getQueueStatus() });
});

router.get('/agents/:id', (req, res) => {
  const agent = bgAgents.getAgent(req.params.id);
  if (!agent) return res.status(404).json({ error: 'Agent not found' });
  res.json(agent);
});

router.get('/agents/:id/result', (req, res) => {
  const result = bgAgents.getResult(req.params.id);
  if (result === null) return res.status(404).json({ error: 'Agent not found' });
  res.json({ result });
});

router.delete('/agents/:id', (req, res) => {
  const result = bgAgents.cancelAgent(req.params.id);
  res.json(result);
});

// ── Training Data ──

const training = require('../training');

router.get('/training/preview', (req, res) => {
  try {
    const preview = training.previewExport({
      minToolCalls: parseInt(req.query.minTools) || 2,
      project: req.query.project || null,
    });
    res.json(preview);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

router.post('/training/export', (req, res) => {
  try {
    const result = training.exportTrainingData({
      format: req.body.format || 'chatml',
      project: req.body.project || null,
      minToolCalls: req.body.minToolCalls || 2,
      includeExperience: req.body.includeExperience !== false,
      systemPrompt: req.body.systemPrompt || null,
      maxSamples: req.body.maxSamples || 10000,
    });
    res.json(result);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

router.get('/training/exports', (_req, res) => {
  res.json(training.listExports());
});

// ── Fine-tuning (tinygrad training) ──

const tinygradTrain = require('../tinygrad-train');

router.get('/training/jobs', (_req, res) => {
  res.json(tinygradTrain.listJobs());
});

router.post('/training/finetune', (req, res) => {
  try {
    const result = tinygradTrain.startTraining(req.body);
    res.json(result);
  } catch (e) {
    res.status(400).json({ error: e.message });
  }
});

router.get('/training/jobs/:id', (req, res) => {
  const job = tinygradTrain.getJob(req.params.id);
  if (!job) return res.status(404).json({ error: 'Job not found' });
  res.json(job);
});

router.delete('/training/jobs/:id', (req, res) => {
  const result = tinygradTrain.cancelJob(req.params.id);
  res.json(result);
});

router.get('/training/adapters', (_req, res) => {
  res.json(tinygradTrain.listAdapters());
});

// ── Calibration ──

const calibration = require('../calibration');

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

router.delete('/calibration', (_req, res) => {
  calibration.saveProfile(calibration.defaultProfile());
  res.json({ success: true });
});

// ── Knowledge Graph ──

const kg = require('../knowledge-graph');

router.get('/graph/stats', (_req, res) => {
  res.json(kg.getStats());
});

router.get('/graph/entities', (req, res) => {
  const type = req.query.type || null;
  res.json(kg.listEntities(type));
});

router.get('/graph/query', (req, res) => {
  const q = req.query.q || '';
  if (!q) return res.json({ matches: [], context: '' });
  res.json(kg.queryGraph(q));
});

router.get('/graph/entity/:name', (req, res) => {
  const entity = kg.getEntity(req.params.name);
  if (!entity) return res.status(404).json({ error: 'Not found' });
  const neighbors = kg.getNeighbors(entity.id);
  res.json({ ...entity, neighbors });
});

router.get('/graph/subgraph/:name', (req, res) => {
  const hops = parseInt(req.query.hops) || 2;
  res.json(kg.getSubgraph(req.params.name, hops));
});

router.post('/graph/build', async (_req, res) => {
  try {
    const result = await kg.buildFromMemories();
    res.json(result);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// ── Tool Telemetry ──

const telemetry = require('../telemetry');

router.get('/tools/stats', (req, res) => {
  const days = req.query.days ? parseInt(req.query.days, 10) : undefined;
  res.json(telemetry.stats({ days }));
});

router.get('/tools/stats/:tool', (req, res) => {
  const days = req.query.days ? parseInt(req.query.days, 10) : undefined;
  res.json(telemetry.stats({ tool: req.params.tool, days }));
});

// ── Skills ──

router.get('/skills/effectiveness', (_req, res) => {
  const skills = require('../skills');
  res.json(skills.getEffectivenessReport());
});

router.get('/skills/stale', (_req, res) => {
  const { loadCustomTools } = require('../custom-tools');
  const tools = loadCustomTools();
  const thirtyDaysAgo = Date.now() - (30 * 24 * 60 * 60 * 1000);
  const stale = tools.filter(t =>
    t.source === 'auto' &&
    (t.usage_count || 0) === 0 &&
    t.created && new Date(t.created).getTime() < thirtyDaysAgo
  );
  res.json(stale.map(t => ({ name: t.name, description: t.description, created: t.created })));
});

router.delete('/skills/:name', (req, res) => {
  const { loadCustomTools, deleteCustomTool } = require('../custom-tools');
  const name = req.params.name;
  const tools = loadCustomTools();
  const tool = tools.find(t => t.name === name);
  if (!tool) return res.status(404).json({ error: `Skill "${name}" not found` });
  if (tool.source !== 'auto') return res.status(400).json({ error: 'Only auto-generated skills can be deleted via this endpoint' });
  deleteCustomTool(name);
  res.json({ ok: true, message: `Deleted skill "${name}"` });
});

module.exports = router;
