<?php

/**
 * Prescribing option-format rules for the form-based SBA generator only.
 */

/**
 * @return list<string>
 */
function sbaPrescribingLearningPointKeys(): array
{
    return [
        'drug_selection',
        'route_selection',
        'dose_selection',
        'frequency_duration_selection',
        'allergy_avoidance',
    ];
}

/**
 * @param array<string, mixed> $question
 */
function sbaPrescribingInferLearningPoint(array $question): string
{
    $tutor = trim((string) ($question['_tutor_comments'] ?? ''));
    $lead = isset($question['lead_in']) ? trim((string) $question['lead_in']) : '';
    $blob = mb_strtolower($tutor . "\n" . $lead);

    if ($blob !== '' && preg_match(
        '/\b(?:penicillin|beta[\s-]?lactam|drug)\s+allerg|\ballerg(?:y|ic)\s+to\b|\bavoid\b.{0,40}\b(?:penicillin|amoxicillin|antibiotic)\b|\bcontraindicat|\bsafe\s+alternative\b/i',
        $blob
    )) {
        return 'allergy_avoidance';
    }

    if (function_exists('sbaStyleTutorCommentsRequestDosingDetail')
        && sbaStyleTutorCommentsRequestDosingDetail($question)) {
        if (preg_match('/\b(?:frequency|duration|how\s+long|course\s+length)\b/i', $blob)) {
            return 'frequency_duration_selection';
        }

        return 'dose_selection';
    }

    if ($blob !== '' && preg_match(
        '/\b(?:which\s+dose|what\s+dose|dose\s+of|dosing|how\s+many\s+mg|milligrams?\s+per|mg\s*\/\s*kg|loading\s+dose|maintenance\s+dose)\b/i',
        $blob
    )) {
        return 'dose_selection';
    }

    if ($blob !== '' && preg_match(
        '/\b(?:frequency|duration|how\s+long\s+should|course\s+length|for\s+how\s+many\s+days|twice\s+daily\s+or\s+three)\b/i',
        $blob
    )) {
        return 'frequency_duration_selection';
    }

    if ($blob !== '' && preg_match(
        '/\b(?:which\s+route|what\s+route|route\s+of\s+administration|oral\s+or\s+(?:iv|intravenous)|intravenous\s+or\s+oral|parenteral\s+or\s+oral)\b/i',
        $blob
    )) {
        return 'route_selection';
    }

    $sk = trim((string) ($question['_current_skill'] ?? ''));
    if (preg_match('/^prescribing$/i', $sk)) {
        $condition = trim((string) ($question['_condition_name'] ?? ''));
        if (function_exists('sbaGeneratorConditionLooksCommunityAcquiredPneumonia')
            && sbaGeneratorConditionLooksCommunityAcquiredPneumonia($condition)
            && $tutor === '') {
            return 'drug_selection';
        }

        return 'drug_selection';
    }

    return '';
}

function sbaPrescribingLearningPointRequiresStructuredRegimens(string $learningPoint): bool
{
    return in_array($learningPoint, ['dose_selection', 'frequency_duration_selection'], true);
}

function sbaPrescribingLearningPointAllowsRouteInOptions(string $learningPoint): bool
{
    return in_array($learningPoint, ['route_selection', 'dose_selection', 'frequency_duration_selection'], true);
}

function sbaStyleOptionLineIncludesPrescribingDoseOrFrequency(string $line): bool
{
    if ($line === '') {
        return false;
    }
    if (preg_match('/\b\d+(?:\.\d+)?\s*(?:mg|g|mcg|µg|micrograms?|units?)\b/i', $line)) {
        return true;
    }

    return (bool) preg_match(
        '/\b(?:once|twice|three\s+times|four\s+times)\s+(?:daily|a\s+day)\b|\b(?:od|bd|tds|qds)\b|\bevery\s+\d+\s*(?:h|hours?)\b|\bfor\s+\d+\s+days?\b|\b\d+\s+days?\s+course\b/i',
        $line
    );
}

function sbaStyleOptionLineIncludesPrescribingRoute(string $line): bool
{
    if ($line === '') {
        return false;
    }

    return (bool) preg_match(
        '#\b(?:orally|oral|intravenous|intramuscular|subcutaneous|inhaled|nebulised|nebuli[sz]ed|topical|sublingual|rectal|transdermal|iv|im|sc)\b#i',
        $line
    );
}

function sbaStyleOptionLineLooksLikeFullPrescribingRegimen(string $line): bool
{
    return sbaStyleOptionLineIncludesPrescribingDoseOrFrequency($line)
        && (sbaStyleOptionLineIncludesPrescribingRoute($line)
            || preg_match('#\b(?:orally|oral|intravenous|iv)\b#i', $line));
}

/**
 * @param array<string, string> $opts
 */
function sbaPrescribingCountOptionsWithDoseOrFrequency(array $opts): int
{
    $n = 0;
    foreach ($opts as $t) {
        if (sbaStyleOptionLineIncludesPrescribingDoseOrFrequency($t)) {
            ++$n;
        }
    }

    return $n;
}

/**
 * @param array<string, mixed> $question
 */
function sbaPrescribingShouldRelaxOptionSimilarityAndLengthWarnings(array $question): bool
{
    $point = sbaPrescribingInferLearningPoint($question);

    return sbaPrescribingLearningPointRequiresStructuredRegimens($point);
}

/**
 * @param array<string, mixed> $job
 */
function buildSbaGeneratorPrescribingOptionFormatPromptBlock(array $job): string
{
    $skill = trim((string) ($job['skill'] ?? ''));
    if (!preg_match('/^prescribing$/i', $skill)) {
        return '';
    }

    $tutor = trim((string) ($job['tutor_comments'] ?? ''));
    $condition = (string) ($job['condition_name'] ?? '');
    $isCap = function_exists('sbaGeneratorConditionLooksCommunityAcquiredPneumonia')
        && sbaGeneratorConditionLooksCommunityAcquiredPneumonia($condition);

    $lines = [];
    $lines[] = 'BINDING — PRESCRIBING OPTION FORMAT (Current skill = Prescribing)';
    $lines[] = 'Decide **one** prescribing learning point and keep **all five options** in the **same format** (prescribing choices only — not admission, referral, or investigation).';
    $lines[] = '';
    $lines[] = '**Learning points (choose exactly one unless Tutor comments specify otherwise):**';
    $lines[] = '1. **Drug selection** (default for CAP and most undergraduate antimicrobial items) — options are **drug names only**, or **drug + route** when route discrimination matters. **Do not** include dose, mg strength, or frequency (TDS/BD/daily) unless Tutor comments or the lead-in explicitly test dosing.';
    $lines[] = '   - Example: **A. Amoxicillin** | **B. Doxycycline** | **C. Clarithromycin** | **D. Co-amoxiclav** | **E. Ciprofloxacin**';
    $lines[] = '2. **Route selection** — same drug class or parallel drugs with **route** compared consistently (e.g. oral amoxicillin vs IV co-amoxiclav).';
    $lines[] = '3. **Dose selection** — **same drug** in every option with **different doses** (or clearly comparable dose regimens); stem/lead-in/Tutor comments must make dose the task.';
    $lines[] = '4. **Frequency / duration selection** — **same drug and dose band** with different **frequency or course length**; stem/lead-in/Tutor comments must make this the task.';
    $lines[] = '5. **Allergy / contraindication avoidance** — options remain **prescribing choices**, but the stem documents allergy/contraindication and distractors test unsafe choices; prefer **short drug-name options** unless testing a specific contraindicated regimen.';
    $lines[] = '';
    if ($isCap && $tutor === '') {
        $lines[] = '**Community-acquired pneumonia (no Tutor comments):** default to **drug selection** — **drug names only** in options A–E (no “500 mg orally three times daily” on every line). The **keyed** answer text may match the option style (drug name only).';
        $lines[] = '';
    }
    $lines[] = '**Parallel structure:** keep options in a **similar length band** — avoid four long “drug + mg + route + frequency” lines with one short drug name (or the reverse).';
    $lines[] = '**Do not** put full chart-style regimens on every option when the lead-in asks **which antibiotic** / **most appropriate drug** / **first-line treatment** without mentioning dose or frequency.';

    return "\n" . embedPromptField(implode("\n", $lines), 5500) . "\n";
}
