<?php

/**
 * Form-based SBA generator: skill list resolution for multi-question jobs.
 */

/**
 * @return list<string>
 */
function formGeneratorAllowedSkillNames(): array
{
    return [
        'Diagnosis',
        'Investigation',
        'Interpretation',
        'Management',
        'Prescribing',
        'Emergency Management',
        'Monitoring',
    ];
}

function sbaGeneratorConditionLooksAcuteCoronarySyndrome(string $conditionName): bool
{
    $c = mb_strtolower(trim($conditionName));

    return (bool) preg_match(
        '/\bacute\s+coronary\s+syndrome\b|\bacs\b|\b(?:stemi|nstemi|myocardial\s+infarction|heart\s+attack)\b/i',
        $c
    );
}

function sbaGeneratorConditionLooksAsthma(string $conditionName): bool
{
    return (bool) preg_match('/\basthma\b/i', mb_strtolower(trim($conditionName)));
}

/**
 * Condition-aware default skill rotation order (no repeats until the list is exhausted).
 *
 * @return list<string>
 */
function formGeneratorDefaultSkillSetForCondition(string $conditionName, string $presentation = ''): array
{
    $sepsisPath = dirname(__DIR__) . '/../prompts/sba_sepsis_batch_concepts.php';
    if (is_readable($sepsisPath)) {
        require_once $sepsisPath;
    }
    $pePath = dirname(__DIR__) . '/../prompts/sba_pe_emergency_concepts.php';
    if (is_readable($pePath)) {
        require_once $pePath;
    }
    $capPath = dirname(__DIR__) . '/../prompts/sba_cap_prescribing_concepts.php';
    if (is_readable($capPath)) {
        require_once $capPath;
    }

    if (function_exists('sbaGeneratorConditionLooksSepsis') && sbaGeneratorConditionLooksSepsis($conditionName)) {
        return ['Diagnosis', 'Investigation', 'Interpretation', 'Management', 'Emergency Management'];
    }
    if (function_exists('sbaGeneratorConditionLooksPulmonaryEmbolism')
        && sbaGeneratorConditionLooksPulmonaryEmbolism($conditionName)) {
        return ['Diagnosis', 'Investigation', 'Interpretation', 'Management', 'Emergency Management'];
    }
    if (function_exists('sbaGeneratorConditionLooksCommunityAcquiredPneumonia')
        && sbaGeneratorConditionLooksCommunityAcquiredPneumonia($conditionName)) {
        return ['Diagnosis', 'Investigation', 'Prescribing', 'Monitoring', 'Management'];
    }
    if (sbaGeneratorConditionLooksAcuteCoronarySyndrome($conditionName)) {
        return ['Diagnosis', 'Investigation', 'Interpretation', 'Management', 'Emergency Management'];
    }
    if (sbaGeneratorConditionLooksAsthma($conditionName)) {
        return [
            'Diagnosis',
            'Investigation',
            'Interpretation',
            'Management',
            'Monitoring',
            'Emergency Management',
            'Prescribing',
        ];
    }

    return ['Diagnosis', 'Investigation', 'Interpretation', 'Management', 'Prescribing', 'Monitoring'];
}

/**
 * Single-question jobs: one suitable skill (Diagnosis unless presentation/condition strongly suggests another).
 */
function formGeneratorPickDefaultSkillForSingleQuestion(string $conditionName, string $presentation = ''): string
{
    $blob = mb_strtolower(trim($conditionName . ' ' . $presentation));

    if (preg_match('/\b(?:prescrib|antibiotic|drug\s+choice|oral\s+therapy)\b/i', $blob)) {
        return 'Prescribing';
    }
    if (preg_match('/\b(?:emergency\s+management|resuscitat|cardiac\s+arrest|collapse|unstable|shock|massive\s+pe)\b/i', $blob)) {
        return 'Emergency Management';
    }
    if (preg_match('/\b(?:monitor|follow[\s-]?up\s+review|serial\s+(?:lactate|observations)|surveillance)\b/i', $blob)) {
        return 'Monitoring';
    }
    if (preg_match('/\b(?:interpret|troponin\s+result|ecg\s+shows|result\s+shows)\b/i', $blob)) {
        return 'Interpretation';
    }
    if (preg_match('/\b(?:investigation|initial\s+(?:test|investigation)|which\s+(?:test|investigation))\b/i', $blob)) {
        return 'Investigation';
    }
    if (preg_match('/\b(?:management|treat(?:ment)?|therap(?:y|eutic))\b/i', $blob)) {
        return 'Management';
    }

    $set = formGeneratorDefaultSkillSetForCondition($conditionName, $presentation);
    if (count($set) === 1) {
        return $set[0];
    }

    return 'Diagnosis';
}

/**
 * Tutor-selected skills in canonical catalogue order (one question per skill).
 *
 * @param list<string> $manualSkills from form checkboxes
 * @return list<string>
 */
function formGeneratorNormalizeManualSkillsList(array $manualSkills): array
{
    $allowed = formGeneratorAllowedSkillNames();
    $picked = [];
    foreach ($manualSkills as $sk) {
        $t = trim((string) $sk);
        if ($t !== '' && in_array($t, $allowed, true) && !in_array($t, $picked, true)) {
            $picked[] = $t;
        }
    }
    if ($picked === []) {
        return [];
    }
    $ordered = [];
    foreach ($allowed as $name) {
        if (in_array($name, $picked, true)) {
            $ordered[] = $name;
        }
    }

    return $ordered;
}

/**
 * Resolve skills for a job: manual selection only for new jobs; legacy fallback when empty.
 *
 * @param list<string> $manualSkills from form checkboxes (may be empty)
 * @return list<string>
 */
function formGeneratorResolveJobSkillsList(
    string $conditionName,
    string $presentation,
    array $manualSkills,
    int $numQuestions
): array {
    $ordered = formGeneratorNormalizeManualSkillsList($manualSkills);
    if ($ordered !== []) {
        return $ordered;
    }

    $numQuestions = max(1, $numQuestions);
    if ($numQuestions <= 1) {
        return [formGeneratorPickDefaultSkillForSingleQuestion($conditionName, $presentation)];
    }

    return formGeneratorDefaultSkillSetForCondition($conditionName, $presentation);
}

/**
 * @param list<string> $skills
 */
function formGeneratorSkillsListToJobCsv(array $skills): string
{
    return implode(',', $skills);
}

/**
 * Skill for question N in a job (1-based); rotates with modulo when N > skill count.
 *
 * @param list<string> $skills
 */
function formGeneratorSkillForQuestionNumber(array $skills, int $questionNumber): string
{
    $skills = array_values(array_filter(array_map('trim', $skills)));
    if ($skills === []) {
        return 'Diagnosis';
    }
    $idx = max(0, $questionNumber - 1);
    if ($idx >= count($skills)) {
        $idx = $idx % count($skills);
    }

    return $skills[$idx];
}
