// ============================================================
// PHYSICAL EXAM GUIDE — step-level narrative + list generation
// ============================================================
// Receives a flat array of exam STEPS (each with component name, label,
// method, expected normal, status, and optional abnormal note). Returns
// a professional two-section report (Technique performed + Findings).
// Mirrors the milestone-narrative pattern: same AppRole-injection guard,
// same clinical audit category.

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

router.post('/generate-pe-narrative', authMiddleware, async function (req, res) {
  try {
    var { steps, ageGroup, system, patientAge, patientGender, model, format } = req.body;
    if (!Array.isArray(steps) || steps.length === 0) {
      return res.status(400).json({ error: 'No steps provided' });
    }

    // Partition by assessment status
    var normal   = steps.filter(function (s) { return s.status === 'normal'; });
    var abnormal = steps.filter(function (s) { return s.status === 'abnormal'; });

    if (normal.length === 0 && abnormal.length === 0) {
      return res.json({
        success:   true,
        narrative: 'No physical-exam steps were assessed.',
        summary:   { normal: 0, abnormal: 0, notAssessed: steps.length }
      });
    }

    // Group by component for readability — AI works better with structure.
    function groupByComponent(list) {
      var groups = {};
      list.forEach(function (s) {
        var key = s.component || 'Other';
        if (!groups[key]) groups[key] = [];
        groups[key].push(s);
      });
      return groups;
    }
    var normalGroups   = groupByComponent(normal);
    var abnormalGroups = groupByComponent(abnormal);

    // Build structured text for the model
    var text = '';
    if (Object.keys(normalGroups).length) {
      text += 'NORMAL FINDINGS (grouped by exam component):\n';
      Object.keys(normalGroups).forEach(function (comp) {
        text += '\n[' + comp + ']\n';
        normalGroups[comp].forEach(function (s) {
          text += '  • ' + s.label + '\n';
          text += '      method: ' + (s.method || 'standard method') + '\n';
          text += '      expected normal: ' + (s.normal || 'unspecified') + '\n';
        });
      });
    }
    if (Object.keys(abnormalGroups).length) {
      text += '\nABNORMAL FINDINGS (grouped by exam component):\n';
      Object.keys(abnormalGroups).forEach(function (comp) {
        text += '\n[' + comp + ']\n';
        abnormalGroups[comp].forEach(function (s) {
          text += '  • ' + s.label + '\n';
          text += '      method: ' + (s.method || 'standard method') + '\n';
          text += '      physician note: ' + (s.note || 'abnormal, no detail provided') + '\n';
        });
      });
    }

    var prompt = (format === 'list') ? PROMPTS.peGuideList : PROMPTS.peGuideNarrative;
    var systemLabel = (system === 'neuro') ? 'Neurologic' : 'Musculoskeletal';

    var result = await callAI([
      { role: 'system', content: prompt + INJECTION_GUARD },
      { role: 'user',   content:
        'Patient: ' + (patientAge || 'Unknown') + ', ' + (patientGender || 'Unknown') + '\n' +
        'Age group: ' + (ageGroup || 'Unknown') + '\n' +
        'Exam system: ' + systemLabel + '\n\n' +
        wrapUserText('pe_steps', text) +
        '\n\nAssessed steps: ' + (normal.length + abnormal.length) +
        ' | Normal: ' + normal.length +
        ' | Abnormal: ' + abnormal.length
      }
    ], { model: model });

    res.json({
      success:   true,
      narrative: result.content,
      model:     result.model,
      summary:   { normal: normal.length, abnormal: abnormal.length, notAssessed: steps.length - normal.length - abnormal.length }
    });
    logger.audit(req.user.id, 'generate_pe_narrative', 'Generated PE narrative (' + systemLabel + ')', req, { category: 'clinical' });
  } catch (err) {
    logger.error('POST /generate-pe-narrative', err.message);
    res.status(500).json({ error: 'Request failed' });
  }
});

module.exports = router;
