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

const router = express.Router();

interface VisitEntry { date?: string; type?: string; content?: string; labs?: string }
interface SubspecialtyEntry { date?: string; specialistName?: string; specialty?: string; content?: string; labs?: string }
interface LabEntry { date?: string; values?: string }

// Generate chart review
router.post('/generate-chart-review', authMiddleware, async (req: Request, res: Response) => {
  try {
    const {
      type,
      patientAge, patientGender, pmh,
      visits,
      subspecialty,
      edVisits,
      labs,
      model,
      additionalInstructions,
    } = req.body as {
      type?: 'outpatient' | 'subspecialty' | 'ed';
      patientAge?: string;
      patientGender?: string;
      pmh?: string;
      visits?: VisitEntry[];
      subspecialty?: SubspecialtyEntry[];
      edVisits?: VisitEntry[];
      labs?: LabEntry[];
      model?: string;
      additionalInstructions?: string;
    };

    const today = new Date().toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
    let clinicalData = `Today's date: ${today}\nPatient: ${patientAge || 'Unknown'}, ${patientGender || 'Unknown'}`;
    if (pmh) clinicalData += `\nPMH: ${wrapUserText('pmh', pmh)}`;

    let prompt: string;
    if (type === 'ed') prompt = PROMPTS.chartReviewED;
    else if (type === 'subspecialty') prompt = PROMPTS.chartReviewSubspecialty;
    else prompt = PROMPTS.chartReviewOutpatient;

    (visits || []).forEach((v) => {
      clinicalData += `\n\n=== OUTPATIENT VISIT (${v.date}) ===\n` + wrapUserText('visit', v.content || '');
      if (v.labs && v.labs.trim()) clinicalData += `\n--- Labs from this visit (${v.date}) ---\n` + wrapUserText('labs', v.labs);
    });
    (subspecialty || []).forEach((s) => {
      clinicalData += `\n\n=== SUBSPECIALTY: ${(s.specialty || 'Subspecialty').toUpperCase()} — ${s.specialistName || 'Unknown'} (${s.date}) ===\n` + wrapUserText('consult', s.content || '');
      if (s.labs && s.labs.trim()) clinicalData += `\n--- Labs from this visit (${s.date}) ---\n` + wrapUserText('labs', s.labs);
    });
    (edVisits || []).forEach((v) => {
      clinicalData += `\n\n=== ED VISIT (${v.date}) ===\n` + wrapUserText('ed_visit', v.content || '');
      if (v.labs && v.labs.trim()) clinicalData += `\n--- Labs from this visit (${v.date}) ---\n` + wrapUserText('labs', v.labs);
    });

    if (labs && labs.length > 0) {
      clinicalData += '\n\n=== ADDITIONAL LABS (not tied to a specific visit) ===';
      labs.forEach((l) => { clinicalData += `\n${l.date ? l.date + ': ' : ''}` + wrapUserText('labs', l.values || ''); });
    }

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

    const result = await callAI([
      { role: 'system', content: prompt + INJECTION_GUARD },
      { role: 'user', content: clinicalData },
    ], { model, maxTokens: 4000 });

    res.json({ success: true, review: result.content, model: result.model });
    logger.audit(req.user!.id, 'generate_chart_review', 'Generated chart review', req, { category: 'clinical' });
  } catch (err) {
    res.status(500).json({ error: 'Request failed' });
  }
});

export = router;
