// ============================================================
// REFINE ROUTES — Modify, shorten, clarify any document
// ============================================================

import express = require('express');
import type { Request, Response } from 'express';
const { callAI } = require('../utils/ai');
const PROMPTS = require('../utils/prompts');
const { authMiddleware } = require('../middleware/auth');
const logger = require('../utils/logger');
const { wrapUserText, INJECTION_GUARD } = require('../utils/promptSafe');

const router = express.Router();

router.post('/refine', authMiddleware, async function (req: Request, res: Response) {
  try {
    const { currentDocument, instructions, sourceContext, model } = req.body;
    if (!currentDocument) return res.status(400).json({ error: 'No document to refine' });
    if (!instructions) return res.status(400).json({ error: 'No instructions provided' });

    let userContent = '';
    if (sourceContext) {
      userContent += 'ORIGINAL SOURCE MATERIAL (reference this for any data lookups — labs, notes, history):\n'
        + wrapUserText('source', sourceContext) + '\n\n';
    }
    userContent += 'CURRENT DOCUMENT (modify this based on user instructions):\n'
      + wrapUserText('document', currentDocument)
      + '\n\nUSER INSTRUCTIONS:\n'
      + wrapUserText('instructions', instructions);

    const result = await callAI([
      { role: 'system', content: PROMPTS.refine + INJECTION_GUARD },
      { role: 'user', content: userContent },
    ], { model, maxTokens: 6000 });

    res.json({ success: true, refined: result.content, model: result.model });
    logger.audit(req.user!.id, 'refine_document', 'Refined document', req, { category: 'clinical' });
  } catch (err) {
    res.status(500).json({ error: 'Request failed' });
  }
});

router.post('/shorten', authMiddleware, async function (req: Request, res: Response) {
  try {
    const { document, model } = req.body;
    if (!document) return res.status(400).json({ error: 'No document' });

    const result = await callAI([
      { role: 'system', content: PROMPTS.shortenDocument + INJECTION_GUARD },
      { role: 'user', content: wrapUserText('document', document) },
    ], { model });

    res.json({ success: true, shortened: result.content, model: result.model });
    logger.audit(req.user!.id, 'shorten_document', 'Shortened document', req, { category: 'clinical' });
  } catch (err) {
    res.status(500).json({ error: 'Request failed' });
  }
});

router.post('/clarify', authMiddleware, async function (req: Request, res: Response) {
  try {
    const { document, context, model } = req.body;
    if (!document) return res.status(400).json({ error: 'No document' });

    const result = await callAI([
      { role: 'system', content: PROMPTS.askClarification + INJECTION_GUARD },
      { role: 'user', content: 'Document type: ' + (context || 'medical document') + '\n\n' + wrapUserText('document', document) },
    ], { model, maxTokens: 1000 });

    res.json({ success: true, questions: result.content, model: result.model });
    logger.audit(req.user!.id, 'clarify_document', 'Generated clarification questions', req, { category: 'clinical' });
  } catch (err) {
    res.status(500).json({ error: 'Request failed' });
  }
});

export = router;
