// ============================================================
// DON'T-MISS TOOLTIP ROUTE — post-note "what to clarify or
// consider" suggestions for sick visit + encounter HPI tabs.
// Hard cap of 5 points. Separate AI pass after note generation
// so the existing note-generation routes stay untouched.
// ============================================================

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

function extractJson(raw) {
  var t = String(raw || '').trim();
  t = t.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/i, '');
  var s = t.indexOf('{');
  if (s > 0) t = t.substring(s);
  var e = t.lastIndexOf('}');
  if (e > -1 && e < t.length - 1) t = t.substring(0, e + 1);
  try { return JSON.parse(t); } catch (err) { return null; }
}

// ── POST /dont-miss — return up to 5 high-yield items ─────
// Body:
//   noteText        — generated note (required)
//   noteType        — 'hpi' | 'sickvisit' (informational, included in context)
//   patientAge      — string, optional but strongly preferred
//   chiefComplaint  — string, optional (sick visit has it; encounter HPI doesn't)
//   model           — optional override
// Returns: { success, points: [{point, why}], model }
router.post('/dont-miss', async function (req, res) {
  var start = Date.now();
  try {
    var { noteText, noteType, patientAge, chiefComplaint, model } = req.body;
    if (!noteText || !noteText.trim()) {
      return res.status(400).json({ error: 'noteText is required' });
    }

    var context = 'NOTE TYPE: ' + (noteType || 'unknown') + '\n';
    context += 'PATIENT AGE: ' + (patientAge || 'unknown') + '\n';
    if (chiefComplaint && chiefComplaint.trim()) {
      context += 'CHIEF COMPLAINT: ' + wrapUserText('chief_complaint', chiefComplaint) + '\n';
    }
    context += '\nGENERATED NOTE:\n' + wrapUserText('note', noteText);

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

    var parsed = extractJson(result.content);
    var points = (parsed && Array.isArray(parsed.points)) ? parsed.points : [];
    points = points
      .filter(function (p) { return p && p.point; })
      .map(function (p) { return { point: String(p.point).trim(), why: String(p.why || '').trim() }; })
      .slice(0, 5); // hard cap defense, even if the model ignored the prompt cap

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

    res.json({ success: true, points: points, model: result.model });
  } catch (e) {
    logger.error('[dontMiss] failed', e.message);
    res.status(500).json({ error: 'Request failed' });
  }
});

module.exports = router;
