<?php

ini_set('display_errors', '0');
error_reporting(E_ALL);
ob_start();

header('Content-Type: application/json');

set_error_handler(static function (int $severity, string $message, string $file, int $line): bool {
    error_log('[clinical_safety_review_question] PHP warning: ' . $message . ' in ' . $file . ':' . $line);

    return true;
});

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../ai/form_generator_retry.php';
require_once __DIR__ . '/../ai/form_generator_question_validation.php';
require_once __DIR__ . '/../../prompts/sba_clinical_safety_reviewer_prompt.php';

/**
 * @param array<string, mixed> $payload
 */
function clinicalSafetyJsonResponse(array $payload): void
{
    while (ob_get_level() > 0) {
        ob_end_clean();
    }
    echo json_encode($payload, JSON_UNESCAPED_UNICODE);
    exit;
}

/**
 * @return array{
 *   clinical_safety_rating:string,
 *   clinical_accuracy:string,
 *   one_best_answer:string,
 *   faculty_review_required:bool,
 *   high_priority_concerns:list<string>,
 *   short_summary:string,
 *   clinical_accuracy_rating:string,
 *   one_best_answer_fairness:string,
 *   prescribing_or_monitoring_concerns:list<string>,
 *   stem_key_consistency_concerns:list<string>
 * }
 */
function clinicalSafetyNormalizeApiShape(array $review): array
{
    $clinicalAccuracy = (string) ($review['clinical_accuracy_rating'] ?? $review['clinical_accuracy'] ?? 'borderline');
    $oneBest = (string) ($review['one_best_answer_fairness'] ?? $review['one_best_answer'] ?? 'borderline');

    return [
        'clinical_safety_rating' => (string) ($review['clinical_safety_rating'] ?? 'needs_faculty_review'),
        'clinical_accuracy' => $clinicalAccuracy,
        'one_best_answer' => $oneBest,
        'faculty_review_required' => !empty($review['faculty_review_required']),
        'high_priority_concerns' => is_array($review['high_priority_concerns'] ?? null) ? $review['high_priority_concerns'] : [],
        'short_summary' => (string) ($review['short_summary'] ?? ''),
        // Backward-compatible fields still consumed by current UI renderer.
        'clinical_accuracy_rating' => $clinicalAccuracy,
        'one_best_answer_fairness' => $oneBest,
        'prescribing_or_monitoring_concerns' => is_array($review['prescribing_or_monitoring_concerns'] ?? null)
            ? $review['prescribing_or_monitoring_concerns'] : [],
        'stem_key_consistency_concerns' => is_array($review['stem_key_consistency_concerns'] ?? null)
            ? $review['stem_key_consistency_concerns'] : [],
    ];
}

try {
    $question_id = trim((string) ($_POST['question_id'] ?? ''));

    if ($question_id === '') {
        clinicalSafetyJsonResponse([
            'ok' => false,
            'error' => 'Clinical safety review failed',
            'detail' => 'Missing question ID.',
            'clinical_safety_review' => null,
        ]);
    }

    $sql = 'SELECT * FROM questions WHERE id = :question_id LIMIT 1';
    $stmt = $pdo->prepare($sql);
    $stmt->execute(['question_id' => $question_id]);
    $question = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$question) {
        clinicalSafetyJsonResponse([
            'ok' => false,
            'error' => 'Clinical safety review failed',
            'detail' => 'Question not found.',
            'clinical_safety_review' => null,
        ]);
    }

    if (($question['source_type'] ?? '') !== 'generated') {
        clinicalSafetyJsonResponse([
            'ok' => false,
            'error' => 'Clinical safety review failed',
            'detail' => 'Clinical safety review is only available for generated SBA questions.',
            'clinical_safety_review' => null,
        ]);
    }

    $question = formGeneratorApplyStyleRepairToQuestionRow($question);

    $reviewTarget = $question;
    $reviewSource = 'original_draft';
    $repairBlockedReasons = [];
    $blockedRaw = $_POST['repair_blocked_reasons'] ?? '';
    if (is_string($blockedRaw) && trim($blockedRaw) !== '') {
        $decodedBlocked = json_decode($blockedRaw, true);
        if (is_array($decodedBlocked)) {
            foreach ($decodedBlocked as $r) {
                $t = trim((string) $r);
                if ($t !== '') {
                    $repairBlockedReasons[] = $t;
                }
            }
        }
    }

    $overrideRaw = $_POST['question_override'] ?? '';
    if (is_string($overrideRaw) && trim($overrideRaw) !== '' && $repairBlockedReasons === []) {
        $override = json_decode($overrideRaw, true);
        if (is_array($override)) {
            $reviewTarget = formGeneratorMergeQuestionRowWithContentOverride($question, $override);
            $reviewSource = 'repaired_preview';
        }
    }

    $styleWarnings = [];
    $warningsRaw = $_POST['style_warnings'] ?? '';
    if (is_string($warningsRaw) && $warningsRaw !== '') {
        $decoded = json_decode($warningsRaw, true);
        if (is_array($decoded)) {
            $styleWarnings = $decoded;
        }
    }

    if ($styleWarnings === []) {
        $styleWarnings = formGeneratorStyleWarningsForQuestionRow($reviewTarget, $pdo);
    }

    $result = formGeneratorRunClinicalSafetyReviewForQuestion($reviewTarget, $styleWarnings, [
        'review_source' => $reviewSource,
        'repair_blocked_reasons' => $repairBlockedReasons,
    ]);
    if (!$result['ok'] || !is_array($result['data'])) {
        clinicalSafetyJsonResponse([
            'ok' => false,
            'error' => 'Clinical safety review failed',
            'detail' => $result['error'] !== '' ? (string) $result['error'] : 'Clinical safety review failed.',
            'clinical_safety_review' => null,
        ]);
    }

    clinicalSafetyJsonResponse([
        'ok' => true,
        'clinical_safety_review' => clinicalSafetyNormalizeApiShape($result['data']),
        'review_source' => $reviewSource,
        'reviewed_at' => gmdate('c'),
    ]);
} catch (Throwable $e) {
    error_log('[clinical_safety_review_question] Exception: ' . $e->getMessage());
    clinicalSafetyJsonResponse([
        'ok' => false,
        'error' => 'Clinical safety review failed',
        'detail' => 'Unexpected server error during clinical safety review.',
        'clinical_safety_review' => null,
    ]);
} finally {
    restore_error_handler();
}
