// ============================================================
// 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.

import express = require('express');
import type { Request, Response } from 'express';
const { callAI } = require('../utils/ai');
const PROMPTS = require('../utils/prompts');
const { wrapUserText, INJECTION_GUARD } = require('../utils/promptSafe');
const { authMiddleware } = require('../middleware/auth');
const logger = require('../utils/logger');

const router = express.Router();

interface PeStep {
  component?: string;
  label: string;
  method?: string;
  normal?: string;
  status?: 'normal' | 'abnormal' | null;
  note?: string;
}

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

    const normal = steps.filter((s) => s.status === 'normal');
    const abnormal = steps.filter((s) => 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 },
      });
    }

    function groupByComponent(list: PeStep[]): Record<string, PeStep[]> {
      const groups: Record<string, PeStep[]> = {};
      list.forEach((s) => {
        const key = s.component || 'Other';
        if (!groups[key]) groups[key] = [];
        groups[key].push(s);
      });
      return groups;
    }
    const normalGroups = groupByComponent(normal);
    const abnormalGroups = groupByComponent(abnormal);

    let text = '';
    if (Object.keys(normalGroups).length) {
      text += 'NORMAL FINDINGS (grouped by exam component):\n';
      Object.keys(normalGroups).forEach((comp) => {
        text += '\n[' + comp + ']\n';
        normalGroups[comp].forEach((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((comp) => {
        text += '\n[' + comp + ']\n';
        abnormalGroups[comp].forEach((s) => {
          text += '  • ' + s.label + '\n';
          text += '      method: ' + (s.method || 'standard method') + '\n';
          text += '      physician note: ' + (s.note || 'abnormal, no detail provided') + '\n';
        });
      });
    }

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

    const 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 });

    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: any) {
    logger.error('POST /generate-pe-narrative', err.message);
    res.status(500).json({ error: 'Request failed' });
  }
});

export = router;
