<?php

/**
 * Community-acquired pneumonia — skill-specific rules (main SBA generator only).
 */

require_once __DIR__ . '/sba_cap_prescribing_concepts.php';

function sbaGeneratorConditionLooksCapForSkills(string $conditionName, string $presentation = ''): bool
{
    if (sbaGeneratorConditionLooksCommunityAcquiredPneumonia($conditionName)) {
        return true;
    }
    $blob = mb_strtolower(trim($conditionName . ' ' . $presentation));

    return (bool) preg_match('/\bcommunity[\s-]*acquired\s+pneumonia\b|\bcommunity\s+acquired\s+pneumonia\b|\bcap\b/i', $blob);
}

/**
 * @param array<string, mixed> $job
 */
function buildSbaGeneratorCapEmergencyPromptBlock(array $job): string
{
    $condition = (string) ($job['condition_name'] ?? '');
    $skill = trim((string) ($job['skill'] ?? ''));
    if (!sbaGeneratorConditionLooksCapForSkills($condition, (string) ($job['presentation'] ?? ''))
        || !preg_match('/^emergency\s+management$/i', $skill)) {
        return '';
    }

    $lines = [];
    $lines[] = 'BINDING — COMMUNITY-ACQUIRED PNEUMONIA EMERGENCY MANAGEMENT (Current skill = Emergency Management)';
    $lines[] = '**Options:** urgent **management / resuscitation / escalation** actions only — **not** investigations, imaging, or “await results”.';
    $lines[] = '**Hypoxic severe CAP / sepsis-style pneumonia (mandatory when SpO₂ is below about 92% on breathing air, or clearly hypoxic):**';
    $lines[] = '- The keyed answer should usually include **oxygen therapy** (or supplemental oxygen) **in the same line** as other urgent treatment — e.g. **oxygen plus IV fluids plus broad-spectrum IV antibiotics**, or **oxygen plus IV antibiotics plus urgent escalation** — unless the **lead-in** explicitly asks for a **non-respiratory** step only (e.g. next vasopressor after resuscitation already given).';
    $lines[] = '- If **oxygen** appears in a distractor and the patient is **hypoxic** under a **generic immediate-management** lead-in, either **include oxygen in the key** or **remove the standalone oxygen distractor** — do **not** key **IV fluids plus antibiotics alone** while **oxygen therapy only** or **oxygen plus …** competes as a distractor.';
    $lines[] = '- For **hypotension / septic shock** with pneumonia, the key should reflect **resuscitation** (fluids, IV antibiotics) **and oxygen when hypoxic**, plus **urgent escalation** when severity warrants — not antibiotics alone when the stem shows shock and hypoxia.';
    $lines[] = '**Distractors:** use **plausible but incomplete** emergency strategies (delayed escalation, inadequate resuscitation, oral antibiotics when unstable, ward monitoring) — **not** throwaway **oxygen-only** lines when the key is a **combined** bundle that omits oxygen in a hypoxic patient.';
    $lines[] = '**Do not** use isolated **oxygen-only** as a distractor when the keyed answer is **fluids plus antibiotics** (or similar combined action) **without oxygen** and the stem is **hypoxic**.';

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

/**
 * @param array<string, mixed> $job
 */
function buildSbaGeneratorCapInterpretationPromptBlock(array $job): string
{
    $condition = (string) ($job['condition_name'] ?? '');
    $skill = trim((string) ($job['skill'] ?? ''));
    if (!sbaGeneratorConditionLooksCapForSkills($condition, (string) ($job['presentation'] ?? ''))
        || !preg_match('/^interpretation$/i', $skill)) {
        return '';
    }

    $lines = [];
    $lines[] = 'BINDING — COMMUNITY-ACQUIRED PNEUMONIA INTERPRETATION (Current skill = Interpretation)';
    $lines[] = '**Options:** interpretations or severity labels only — **no** treatment, prescribing, or “next step” actions.';
    $lines[] = '**Lead-in:** interpretation of **supplied findings** only.';
    $lines[] = '**Severity calibration (mandatory):**';
    $lines[] = '- If the intended teaching point is **severe CAP**, include **physiological severity cues** in the stem (e.g. **oxygen saturation**, **respiratory rate**, **blood pressure**, **confusion**, **urea**, **CURB-65 / CRB-65**, or clear **sepsis / shock** features) — not only **CRP**, **WBC**, and **chest X-ray infiltrates**.';
    $lines[] = '- If the stem supplies **only** inflammatory markers and **imaging** without physiological severity data, key **pneumonia / infection** interpretation (e.g. **community-acquired pneumonia likely**) — **do not** overclaim **severe infection** or **severe CAP** without supporting observations.';
    $lines[] = '- When severity scores or hypoxia are present, the keyed interpretation may include **severe** wording consistent with the data.';

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

/**
 * @param array<string, mixed> $job
 */
function buildSbaGeneratorCapManagementPromptBlock(array $job): string
{
    $condition = (string) ($job['condition_name'] ?? '');
    $skill = trim((string) ($job['skill'] ?? ''));
    if (!sbaGeneratorConditionLooksCapForSkills($condition, (string) ($job['presentation'] ?? ''))
        || !preg_match('/^management$/i', $skill)) {
        return '';
    }

    $lines = [];
    $lines[] = 'BINDING — COMMUNITY-ACQUIRED PNEUMONIA MANAGEMENT (Current skill = Management)';
    $lines[] = '**Options:** broader **management strategies** where possible (e.g. **outpatient oral antibiotics**, **hospital admission**, **oxygen and IV antibiotics**, **urgent senior review**, **switch to broader oral cover**) — **not** five parallel **antibiotic drug names only** unless **Tutor comments** explicitly test antibiotic choice under Management.';
    $lines[] = '**Antibiotic selection** belongs under **Prescribing** in a mixed batch — keep **Management** distinct from **Prescribing** (different keyed concept).';
    $lines[] = 'If one option must name a drug, keep **all five** at the same decision level (e.g. all admission/escalation decisions, or all route/setting decisions) — do **not** make the whole set **only** amoxicillin vs co-amoxiclav vs doxycycline unless Prescribing is the Current skill.';

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

/**
 * @param array<string, mixed> $job
 */
function buildSbaGeneratorCapMonitoringPromptBlock(array $job): string
{
    $condition = (string) ($job['condition_name'] ?? '');
    $skill = trim((string) ($job['skill'] ?? ''));
    if (!sbaGeneratorConditionLooksCapForSkills($condition, (string) ($job['presentation'] ?? ''))
        || !preg_match('/^monitoring$/i', $skill)) {
        return '';
    }

    $lines = [];
    $lines[] = 'BINDING — COMMUNITY-ACQUIRED PNEUMONIA MONITORING (Current skill = Monitoring)';
    $lines[] = '**Options:** **monitoring parameters or review actions** at follow-up (e.g. **oxygen saturation**, **respiratory rate**, **temperature**, **symptoms**, **clinical stability**, **inflammatory markers when relevant**, **treatment response**, **adherence**) — homogeneous monitoring family.';
    $lines[] = '**Do not** mix **one-off diagnostic investigations** (e.g. **CT chest**, **blood cultures**, **bronchoscopy**) with routine monitoring unless the **learning point** is explicitly investigation choice — not CAP recovery monitoring.';
    $lines[] = '**Narrow lead-in** to the intended monitoring target; add a **stem cue** so one option is clearly best.';

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

/**
 * @param list<string> $lines
 * @param list<array<string, mixed>> $priorRows
 */
function sbaCapAppendBatchMixedSkillAntiRepetitionLines(
    array &$lines,
    array $priorRows,
    string $currentSkill,
    string $conditionName,
    string $jobSkillsCsv
): void {
    if ($priorRows === [] || !sbaGeneratorConditionLooksCapForSkills($conditionName)) {
        return;
    }
    if ($jobSkillsCsv === '' || substr_count(mb_strtolower($jobSkillsCsv), ',') < 1) {
        return;
    }

    $lines[] = '**Community-acquired pneumonia mixed-skill batch (mandatory):**';
    $lines[] = '- **Diagnosis** → competing diagnoses (pneumonia, PE, heart failure, etc.) — not antibiotic names.';
    $lines[] = '- **Investigation** → tests only; align initial vs next investigation with stem data.';
    $lines[] = '- **Interpretation** → severity matched to supplied data; include physiological cues if keying **severe CAP**.';
    $lines[] = '- **Management** → broader strategies — **not** a full antibiotic-only option set (reserve drug choice for **Prescribing**).';
    $lines[] = '- **Prescribing** → antimicrobial choices only; **one scenario slot per item** (see CAP Prescribing batch map).';
    $lines[] = '- **Monitoring** → follow-up monitoring parameters — not diagnostic work-up lines.';
    $lines[] = '- **Emergency Management** → hypoxic unstable CAP: **oxygen plus** resuscitation when appropriate; **distinct** from Management and Prescribing concepts.';
    $lines[] = '- **Do not** repeat the same **keyed concept** or **lead-in template** across skills in this job.';
    $lines[] = '';
}
