<?php

/**
 * Pulmonary embolism — Investigation / Interpretation / mixed-skill batch rules (main SBA generator only).
 */

function sbaGeneratorConditionLooksPulmonaryEmbolismForSkills(string $conditionName, string $presentation = ''): bool
{
    if (function_exists('sbaGeneratorConditionLooksPulmonaryEmbolism')) {
        return sbaGeneratorConditionLooksPulmonaryEmbolism($conditionName);
    }
    $blob = mb_strtolower(trim($conditionName . ' ' . $presentation));

    return (bool) preg_match('/\bpulmonary\s+embol|\bpe\b/i', $blob);
}

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

    $lines = [];
    $lines[] = 'BINDING — PULMONARY EMBOLISM INVESTIGATION (Current skill = Investigation)';
    $lines[] = '**Options:** investigations/tests only — **no** diagnoses, management, or treatment lines.';
    $lines[] = '**Stem demographics:** age, sex, and risk factors must be **internally consistent** (e.g. do **not** state a **man** “takes oral contraceptive(s)” unless an explicit relevant context is given).';
    $lines[] = '**Pre-test probability:** align the keyed investigation with Wells-style logic in the stem:';
    $lines[] = '- **Low/intermediate probability, stable, no shock:** **D-dimer** may be keyed as **initial** test when appropriate; **not** CTPA as first line without high-risk features.';
    $lines[] = '- **High clinical probability, unstable features, or clear need to confirm before treatment:** **CT pulmonary angiogram (CTPA)** or appropriate confirmatory imaging — stem should document **sufficient suspicion** (e.g. hypoxia, tachycardia, pleuritic pain, DVT signs, high Wells score cues).';
    $lines[] = '- If keying **CTPA**, the stem must support **why imaging is justified now** — not a stable low-risk vignette with CTPA as the obvious first test.';
    $lines[] = '**Lead-in:** initial vs next investigation must match what the stem already shows; do **not** embed the exam question in the stem.';

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

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

    $lines = [];
    $lines[] = 'BINDING — PULMONARY EMBOLISM INTERPRETATION (Current skill = Interpretation)';
    $lines[] = '**Options:** interpretations or diagnostic labels only — **no** management, treatment, or “next step” actions.';
    $lines[] = '**Lead-in:** interpretation of **supplied findings** only — do **not** ask what treatment should be given next.';
    $lines[] = '**Definitive imaging:** when the stem quotes a **definitive** CTPA/V-Q result (e.g. **filling defect**, **pulmonary embolism in … artery**), key a **definitive** label such as **“Pulmonary embolism”** or **“Pulmonary embolism in the right pulmonary artery”** — **not** only **“high probability of pulmonary embolism”** or **“likely pulmonary embolism”**.';
    $lines[] = '**Probability wording** is for **pre-test** or **non-diagnostic** contexts only (e.g. Wells score interpretation without imaging result).';
    $lines[] = '**Distractors:** plausible alternative interpretations on the **same data** — not obviously impossible statements.';

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

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

    $lines[] = '**Pulmonary embolism mixed-skill batch (mandatory):**';
    $lines[] = '- Rotate **skills clearly** — each item must match **Current skill** only; options must match that skill (diagnoses / investigations / interpretations / management actions / emergency actions).';
    $lines[] = '- **Diagnosis** → competing diagnoses; **Investigation** → tests only with **consistent demographics**; **Interpretation** → definitive PE label when CTPA shows embolus; **Management** → stable PE anticoagulation at **one specificity level**; **Emergency Management** → massive/shock vs stable — **distinct** from Management.';
    $lines[] = '- **Do not** repeat the same **lead-in template** or **keyed concept** as a prior item in this job.';
    $lines[] = '';
}
