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

// HPI from encounter
router.post('/generate-hpi-encounter', authMiddleware, async (req, res) => {
  try {
    const { transcript, patientAge, patientGender, model, setting, physicianMemories } = req.body;
    if (!transcript || !transcript.trim()) return res.status(400).json({ error: 'Transcript empty' });

    const prompt = (setting === 'inpatient' ? PROMPTS.hpiInpatient : PROMPTS.hpiEncounter) + INJECTION_GUARD;

    var context = 'Patient: ' + (patientAge || 'Unknown') + ', ' + (patientGender || 'Unknown')
      + '\nSetting: ' + (setting || 'outpatient') + '\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, hpi: result.content, model: result.model });
    logger.audit(req.user.id, 'generate_hpi_encounter', 'Generated HPI from encounter', req, { category: 'clinical' });
  } catch (err) {
    res.status(500).json({ error: 'Request failed' });
  }
});

// HPI from dictation
router.post('/generate-hpi-dictation', authMiddleware, async (req, res) => {
  try {
    const { transcript, patientAge, patientGender, model, setting, physicianMemories } = req.body;
    if (!transcript || !transcript.trim()) return res.status(400).json({ error: 'Dictation empty' });

    const prompt = (setting === 'inpatient' ? PROMPTS.hpiInpatient : PROMPTS.hpiDictation) + INJECTION_GUARD;

    var context = 'Patient: ' + (patientAge || 'Unknown') + ', ' + (patientGender || 'Unknown')
      + '\nSetting: ' + (setting || 'outpatient') + '\n\n' + wrapUserText('dictation', 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, hpi: result.content, model: result.model });
    logger.audit(req.user.id, 'generate_hpi_dictation', 'Generated HPI from dictation', req, { category: 'clinical' });
  } catch (err) {
    res.status(500).json({ error: 'Request failed' });
  }
});

module.exports = router;
