// ============================================================
// PATIENT EDUCATION HANDOUTS — parent-facing education generated
// from an existing clinician note.
// ============================================================

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

router.use(authMiddleware);

// ── POST /patient-education ─────────────────────────────────
// Body:
//   noteText       — generated clinician note (required)
//   diagnosis      — optional explicit diagnosis override/context
//   medications    — optional medication list or free text
//   patientAge     — optional, used for age-appropriate language
//   language       — parent preferred language; defaults to English
//   readingLevel   — optional plain-language target
//   model          — optional override
// Returns: { success, handout, model }
router.post('/patient-education', async function(req, res) {
  var start = Date.now();
  try {
    var body = req.body || {};
    var noteText = String(body.noteText || '').trim();
    if (!noteText) return res.status(400).json({ error: 'noteText is required' });

    var language = String(body.language || 'English').trim() || 'English';
    var context = 'PARENT PREFERRED LANGUAGE: ' + language + '\n';
    context += 'PATIENT AGE: ' + (body.patientAge || 'unknown') + '\n';
    context += 'READING LEVEL: ' + (body.readingLevel || 'plain language') + '\n';
    if (body.diagnosis && String(body.diagnosis).trim()) {
      context += 'DIAGNOSIS CONTEXT: ' + wrapUserText('diagnosis', body.diagnosis) + '\n';
    }
    if (body.medications && String(body.medications).trim()) {
      context += 'MEDICATION CONTEXT: ' + wrapUserText('medications', body.medications) + '\n';
    }
    context += '\nCLINICIAN NOTE:\n' + wrapUserText('note', noteText);

    var result = await callAI([
      { role: 'system', content: PROMPTS.patientEducation + INJECTION_GUARD },
      { role: 'user', content: context }
    ], { model: body.model, maxTokens: 1800 });

    var duration = Date.now() - start;
    logger.apiCall(req.user.id, '/api/patient-education', {
      model: result.model,
      tokensInput: result.usage && result.usage.input_tokens,
      tokensOutput: result.usage && result.usage.output_tokens,
      duration: duration,
      statusCode: 200
    });

    res.json({ success: true, handout: String(result.content || '').trim(), model: result.model });
  } catch (e) {
    logger.error('[patientEducation] failed', e.message);
    res.status(500).json({ error: 'Request failed' });
  }
});

module.exports = router;
