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

var express = require('express');
var router = express.Router();
var { callAI } = require('../utils/ai');
var PROMPTS = require('../utils/prompts');
var { authMiddleware } = require('../middleware/auth');
var logger = require('../utils/logger');
var { wrapUserText, INJECTION_GUARD } = require('../utils/promptSafe');

// Refine/modify document with instructions
router.post('/refine', authMiddleware, async function(req, res) {
  try {
    var currentDocument = req.body.currentDocument;
    var instructions = req.body.instructions;
    var sourceContext = req.body.sourceContext;
    var model = req.body.model;

    if (!currentDocument) return res.status(400).json({ error: 'No document to refine' });
    if (!instructions) return res.status(400).json({ error: 'No instructions provided' });

    var 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);

    var result = await callAI([
      { role: 'system', content: PROMPTS.refine + INJECTION_GUARD },
      { role: 'user', content: userContent }
    ], { model: 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' });
  }
});

// Shorten document
router.post('/shorten', authMiddleware, async function(req, res) {
  try {
    var document = req.body.document;
    var model = req.body.model;

    if (!document) return res.status(400).json({ error: 'No document' });

    var result = await callAI([
      { role: 'system', content: PROMPTS.shortenDocument + INJECTION_GUARD },
      { role: 'user', content: wrapUserText('document', document) }
    ], { model: 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' });
  }
});

// Ask AI for clarification questions
router.post('/clarify', authMiddleware, async function(req, res) {
  try {
    var document = req.body.document;
    var context = req.body.context;
    var model = req.body.model;

    if (!document) return res.status(400).json({ error: 'No document' });

    var result = await callAI([
      { role: 'system', content: PROMPTS.askClarification + INJECTION_GUARD },
      { role: 'user', content: 'Document type: ' + (context || 'medical document') + '\n\n' + wrapUserText('document', document) }
    ], { model: 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' });
  }
});

module.exports = router;
