<?php
// =============================================================
//  POST /api/v1/chatbot/ask
//
//  Mobile equivalent of app/nurse/nurse_ai_proxy.php and
//  app/student/student_ai_proxy.php — same data, same prompts, same
//  Gemini call, via the shared services/GeminiChatbotService.php. Scoped
//  to Nurse and Student, matching the thesis's own mobile chatbot scope
//  (Admin/Preceptor chatbot access is "optional" there — not built here;
//  see GeminiChatbotService.php's header comment for why the much larger
//  staff-side app/ai_proxy.php isn't part of this refactor).
//
//  No CSRF check here (unlike the two web pages) — Bearer-token auth
//  already establishes the request came from the authenticated app, which
//  is what CSRF protection exists to substitute for on a cookie-session
//  page; a mobile client with a stolen bearer token has a different, more
//  fundamental problem than CSRF.
//
//  Body: { "messages": [{"role":"user"|"assistant","content":"..."}], "system"?: "..." }
// =============================================================

require_once __DIR__ . '/../_bootstrap.php';
require_once __DIR__ . '/../../../services/GeminiChatbotService.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    Api::error(405, 'MethodNotAllowed', 'Use POST');
}
if (!defined('GEMINI_API_KEY') || strlen(GEMINI_API_KEY) < 20) {
    Api::error(500, 'ServerError', 'AI chatbot is not configured');
}

$account = api_authenticate();
$table   = $account->getTable();
if (!in_array($table, ['rotation_nurses', 'clinical_students'], true)) {
    Api::error(403, 'Forbidden', 'The AI chatbot is available to Rotation Nurses and Clinical Students');
}

$body      = Api::body();
$sanitized = sanitizeChatMessages($body['messages'] ?? []);
if (empty($sanitized)) {
    Api::error(422, 'ValidationError', 'No valid messages provided');
}

$context = $table === 'rotation_nurses'
    ? buildNurseChatContext($conn, $account->getId())
    : buildStudentChatContext($conn, $account->getId());

if ($context === null) {
    Api::error(404, 'ProfileNotFound', ucfirst(str_replace('_', ' ', rtrim($table, 's'))) . ' profile not found');
}

$clientSystem = (!empty($body['system']) && is_string($body['system'])) ? mb_substr(trim($body['system']), 0, 1000) : '';
$system = $context['base_system'] . "\n\n" . ($clientSystem !== '' ? $clientSystem . "\n\n" : '') . $context['live_data'];

$geminiContents = buildGeminiContents($sanitized);
$result = callGemini($system, $geminiContents);

if (!$result['ok']) {
    Api::error($result['http_code'] ?: 500, 'ChatbotError', $result['error'] ?? 'Gemini request failed');
}

Api::success([
    'text'          => $result['text'],
    'model'         => $result['model'],
    'input_tokens'  => $result['input_tokens'],
    'output_tokens' => $result['output_tokens'],
    'safety_blocked' => $result['safety_blocked'],
]);
