// PRE Web GUI — Memory routes (memory CRUD, artifacts, experience, chronos)
const { Router } = require('express');
const path = require('path');
const memorySystem = require('../memory');
const experienceSystem = require('../experience');
const chronosSystem = require('../chronos');
const exportTool = require('../tools/export');
const { ARTIFACTS_DIR } = require('../constants');

const router = Router();

// ── Memory CRUD ──

router.get('/memory', (req, res) => {
  const query = req.query.q || '';
  if (query) {
    const results = memorySystem.searchMemories(query);
    res.json(results.map(m => ({
      filename: m.filename,
      name: m.name,
      description: m.description,
      type: m.type,
      scope: m.scope,
      body: m.body,
      age: memorySystem.memoryAge(m.mtimeMs),
      modified: new Date(m.mtimeMs).toISOString().slice(0, 10),
    })));
  } else {
    res.json(memorySystem.listForAPI());
  }
});

router.get('/memory/:filename', (req, res) => {
  const memory = memorySystem.getMemory(req.params.filename);
  if (!memory) return res.status(404).json({ error: 'Memory not found' });
  res.json(memory);
});

router.post('/memory', (req, res) => {
  const { name, type, description, content, scope } = req.body || {};
  const result = memorySystem.saveMemory({ name, type, description, content, scope });
  if (result.error) return res.status(400).json({ error: result.error });
  res.json(result);
});

router.delete('/memory/:filename', (req, res) => {
  const result = memorySystem.deleteMemory(req.params.filename);
  if (result.error) return res.status(404).json({ error: result.error });
  res.json(result);
});

// ── Artifacts ──

router.post('/artifacts/reveal', (req, res) => {
  const { filePath } = req.body || {};
  if (!filePath) return res.status(400).json({ error: 'filePath required' });

  const resolved = filePath.startsWith('/artifacts/')
    ? path.join(ARTIFACTS_DIR, filePath.replace(/^\/artifacts\//, ''))
    : filePath;

  const fs = require('fs');
  if (!fs.existsSync(resolved)) {
    return res.status(404).json({ error: 'File not found' });
  }

  try {
    require('../platform').revealInFileManager(resolved);
    res.json({ ok: true });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

router.post('/artifacts/export', async (req, res) => {
  const { path: artPath, format, title } = req.body || {};
  if (!artPath) return res.status(400).json({ error: 'path required' });
  if (!['pdf', 'png', 'html'].includes(format)) {
    return res.status(400).json({ error: 'format must be pdf, png, or html' });
  }

  const exportTitle = title || artPath.replace(/^\/artifacts\//, '').replace(/\.[^.]+$/, '').replace(/-[a-z0-9]+$/, '').replace(/-/g, ' ');

  try {
    let result;
    switch (format) {
      case 'pdf':
        result = await exportTool.exportPdf(artPath, exportTitle);
        break;
      case 'png':
        result = await exportTool.exportPng(artPath, exportTitle);
        break;
      case 'html':
        result = await exportTool.exportSelfContainedHtml(artPath, exportTitle);
        break;
    }
    res.json({ path: result.webPath, filename: result.filename });
  } catch (err) {
    console.error(`[export] Error: ${err.message}`);
    res.status(500).json({ error: err.message });
  }
});

// ── Experience Ledger ──

router.get('/experience', (req, res) => {
  const query = req.query.q || '';
  if (query) {
    experienceSystem.searchExperiences(query).then(results => res.json(results)).catch(() => res.json([]));
  } else {
    res.json(experienceSystem.listExperiences());
  }
});

// ── Chronos (temporal awareness) ──

router.get('/chronos/health', (_req, res) => {
  res.json(chronosSystem.maintenanceSummary());
});

router.get('/chronos/staleness', (_req, res) => {
  res.json(chronosSystem.stalenessReport());
});

router.post('/chronos/verify/:filename', (req, res) => {
  const result = chronosSystem.verifyMemory(req.params.filename);
  if (result.error) return res.status(404).json({ error: result.error });
  res.json(result);
});

router.post('/chronos/maintenance', async (_req, res) => {
  try {
    const result = await chronosSystem.runMaintenance();
    res.json(result);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

module.exports = router;
