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

router.post('/generate-soap', authMiddleware, async (req, res) => {
  try {
    const { transcript, patientAge, patientGender, model, type, additionalInstructions, physicianMemories } = req.body;
    if (!transcript || !transcript.trim()) return res.status(400).json({ error: 'Empty input' });

    let prompt;
    switch (type) {
      case 'subjective': prompt = PROMPTS.soapSubjective; break;
      case 'full':
      default: prompt = PROMPTS.soapFull;
    }

    if (additionalInstructions) {
      prompt += '\n\nADDITIONAL INSTRUCTIONS (operator-supplied, trusted):\n' + additionalInstructions;
    }
    prompt += INJECTION_GUARD;

    var context = 'Patient: ' + (patientAge || 'Unknown') + ', ' + (patientGender || 'Unknown') + '\n\n'
      + wrapUserText('transcript', transcript);
    if (physicianMemories) {
      context += '\n\n[STYLE HINTS (low priority — only apply if relevant to the current note, never copy content from these examples)]\n'
        + wrapUserText('style_hints', physicianMemories)
        + '\n[END STYLE HINTS]';
    }

    const result = await callAI([
      { role: 'system', content: prompt },
      { role: 'user', content: context }
    ], { model });

    res.json({ success: true, soap: result.content, model: result.model });
    logger.audit(req.user.id, 'generate_soap', 'Generated SOAP note', req, { category: 'clinical' });
  } catch (err) {
    res.status(500).json({ error: 'Request failed' });
  }
});

module.exports = router;
