// PRE Web GUI — Media routes (voice, RAG, workflows)
const { Router } = require('express');
const fs = require('fs');
const path = require('path');
const os = require('os');

const router = Router();

// ── Voice ──

router.post('/voice/transcribe', async (req, res) => {
  const voiceTool = require('../tools/voice');
  const { audio, mime_type } = req.body;
  if (!audio) return res.status(400).json({ error: 'audio (base64) is required' });
  try {
    const result = await voiceTool.transcribeBuffer(audio, mime_type || 'audio/webm');
    if (result.error) return res.status(500).json({ error: result.error });
    res.json({ text: result.text, model: result.model, language: result.language });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

router.post('/voice/speak', (req, res) => {
  const voiceTool = require('../tools/voice');
  const { text, voice, rate } = req.body;
  if (!text) return res.status(400).json({ error: 'text is required' });
  const result = voiceTool.speak(text, { voice, rate, play: true });
  if (result.error) return res.status(500).json({ error: result.error });
  res.json(result);
});

router.get('/voice/status', (_req, res) => {
  const voiceTool = require('../tools/voice');
  res.json({
    whisper: voiceTool.hasWhisper,
    say: voiceTool.hasSay,
    ffmpeg: voiceTool.hasFfmpeg,
  });
});

// ── RAG ──

router.get('/rag', async (_req, res) => {
  const ragTool = require('../tools/rag');
  const result = await ragTool.rag({ action: 'list' });
  res.json({ text: result });
});

router.get('/rag/:name', async (req, res) => {
  const ragTool = require('../tools/rag');
  const result = await ragTool.rag({ action: 'status', index_name: req.params.name });
  res.json({ text: result });
});

router.post('/rag/index', async (req, res) => {
  const ragTool = require('../tools/rag');
  const { path: dirPath, index_name, recursive } = req.body;
  if (!dirPath) return res.status(400).json({ error: 'path is required' });
  const result = await ragTool.rag({ action: 'index', path: dirPath, index_name, recursive });
  res.json({ text: result });
});

router.post('/rag/search', async (req, res) => {
  const ragTool = require('../tools/rag');
  const { query, index_name, top_k, min_score } = req.body;
  if (!query) return res.status(400).json({ error: 'query is required' });
  const result = await ragTool.rag({ action: 'search', query, index_name, top_k, min_score });
  res.json({ text: result });
});

router.delete('/rag/:name', async (req, res) => {
  const ragTool = require('../tools/rag');
  const result = await ragTool.rag({ action: 'delete', index_name: req.params.name });
  if (result.startsWith('Error') || result.includes('not found')) return res.status(404).json({ error: result });
  res.json({ ok: true, message: result });
});

// ── Workflows ──

router.get('/workflows', (_req, res) => {
  const wfDir = path.join(os.homedir(), '.pre', 'workflows');
  if (!fs.existsSync(wfDir)) return res.json([]);
  const workflows = fs.readdirSync(wfDir)
    .filter(f => f.endsWith('.json'))
    .map(f => {
      try { return JSON.parse(fs.readFileSync(path.join(wfDir, f), 'utf-8')); } catch { return null; }
    })
    .filter(Boolean)
    .sort((a, b) => new Date(b.created) - new Date(a.created));
  res.json(workflows);
});

router.get('/workflows/:name', async (req, res) => {
  const wfTool = require('../tools/workflow');
  const result = await wfTool.workflow({ action: 'show', name: req.params.name });
  if (result.includes('not found')) return res.status(404).json({ error: result });
  res.json({ text: result });
});

router.post('/workflows/:name/replay', async (req, res) => {
  const wfTool = require('../tools/workflow');
  const result = await wfTool.workflow({ action: 'replay', name: req.params.name, speed: req.body.speed || 1.0 });
  res.json({ text: result });
});

router.delete('/workflows/:name', async (req, res) => {
  const wfTool = require('../tools/workflow');
  const result = await wfTool.workflow({ action: 'delete', name: req.params.name });
  if (result.includes('not found')) return res.status(404).json({ error: result });
  res.json({ ok: true, message: result });
});

router.get('/workflows/recording/status', (_req, res) => {
  const wfTool = require('../tools/workflow');
  const status = wfTool.recordingStatus();
  res.json(status || { recording: false });
});

module.exports = router;
