from __future__ import annotations

import json
from pathlib import Path
from typing import Any


PROJECT_ROOT = Path(__file__).resolve().parents[2]
DEFAULT_DATA_PATH = PROJECT_ROOT / "Data" / "template_data_v0.6.json"


def load_template_data(path: str | Path = DEFAULT_DATA_PATH) -> dict[str, Any]:
    with Path(path).open(encoding="utf-8") as handle:
        data = json.load(handle)
    add_comprehensive_procedure_taxonomy(data)
    add_recommended_next_procedure_section(data)
    add_fast_fill_assist(data)
    return data


def find_form(data: dict[str, Any], form_id: str) -> dict[str, Any]:
    for form in data.get("forms", []):
        if form.get("form_id") == form_id:
            return form
    raise KeyError(f"Unknown form_id: {form_id}")


NEXT_PROCEDURE_TEMPLATE = (
    "\n\nRecommended next procedure: Date: {{next_procedure_date}}. "
    "Medication choice: {{next_procedure_medication_choice}}. "
    "Dose: {{next_procedure_dose}}. Technique: {{next_procedure_technique}}. "
    "Patient position: {{next_procedure_patient_position}}. "
    "Premedication: {{next_procedure_premedication}}. "
    "Pre-procedure comments: {{next_procedure_pre_procedure_comments}}. "
    "Intra-procedure comments: {{next_procedure_intra_procedure_comments}}. "
    "Post-procedure comments: {{next_procedure_post_procedure_comments}}."
)

NEXT_PROCEDURE_FIELDS = [
    {
        "section": "Recommended next procedure",
        "key": "next_procedure_date",
        "label": "Recommended next procedure date",
        "default_layer": "No Default",
        "input_type": "date",
        "required": True,
        "options": "",
        "help": "Manual-only. Enter planned date, approximate date, or document N/A if no repeat is planned.",
    },
    {
        "section": "Recommended next procedure",
        "key": "next_procedure_medication_choice",
        "label": "Medication choice",
        "default_layer": "Per-Form Default",
        "input_type": "text",
        "required": True,
        "options": "",
        "help": "Defaults from the current procedure medication/product choice; edit for the next procedure.",
    },
    {
        "section": "Recommended next procedure",
        "key": "next_procedure_dose",
        "label": "Dose",
        "default_layer": "Per-Form Default",
        "input_type": "text",
        "required": True,
        "options": "",
        "help": "Defaults from the current procedure dose/volume/settings; edit for the next procedure.",
    },
    {
        "section": "Recommended next procedure",
        "key": "next_procedure_technique",
        "label": "Technique",
        "default_layer": "Per-Form Default",
        "input_type": "textarea",
        "required": True,
        "options": "",
        "help": "Defaults from current guidance, approach, target, and needle details.",
    },
    {
        "section": "Recommended next procedure",
        "key": "next_procedure_patient_position",
        "label": "Patient position",
        "default_layer": "Per-Form Default",
        "input_type": "text",
        "required": True,
        "options": "",
        "help": "Defaults from the current procedure position; edit if the next procedure should differ.",
    },
    {
        "section": "Recommended next procedure",
        "key": "next_procedure_premedication",
        "label": "Premedication",
        "default_layer": "Per-Form Default",
        "input_type": "textarea",
        "required": False,
        "options": "",
        "help": "Defaults to the current/typical plan; edit for anxiolysis, allergy prophylaxis, antibiotics, or none.",
    },
    {
        "section": "Recommended next procedure",
        "key": "next_procedure_pre_procedure_comments",
        "label": "Pre-procedure comments",
        "default_layer": "Per-Form Default",
        "input_type": "textarea",
        "required": False,
        "options": "",
        "help": "Editable planning comments before the next procedure.",
    },
    {
        "section": "Recommended next procedure",
        "key": "next_procedure_intra_procedure_comments",
        "label": "Intra-procedure comments",
        "default_layer": "Per-Form Default",
        "input_type": "textarea",
        "required": False,
        "options": "",
        "help": "Editable technique comments for the next procedure.",
    },
    {
        "section": "Recommended next procedure",
        "key": "next_procedure_post_procedure_comments",
        "label": "Post-procedure comments",
        "default_layer": "Per-Form Default",
        "input_type": "textarea",
        "required": False,
        "options": "",
        "help": "Editable follow-up and aftercare comments for the next procedure.",
    },
]


COMMON_PROCEDURE_TEMPLATE = """Procedure: {title}
Indication: {{{{side}}}} procedure for {{{{diagnosis}}}}. {{{{clinical_indication}}}} Baseline pain/function: {{{{baseline_pain_function}}}}.

Consent / safety: {{{{consent_phrase}}}} {{{{timeout_phrase}}}} Safety screen: {{{{allergy_infection_anticoagulant_screen}}}}

Setup: The patient was positioned {{{{patient_position}}}}. Skin preparation: {{{{skin_prep}}}} Sterile setup: {{{{sterile_setup}}}} Monitoring: {{{{monitoring}}}}

Guidance: {{{{guidance}}}}. {{{{guidance_phrase}}}} Images: {{{{image_saved}}}}

Technique: Using {{{{transducer_or_equipment}}}}, a {{{{needle}}}} was advanced via {{{{approach}}}} to {{{{target}}}} at {{{{levels_targets}}}}. Needle visualization/path: {{{{needle_visualization}}}} Safety check/aspiration/stimulation: {{{{aspiration_result}}}} Treatment character/spread/response: {{{{injection_character}}}}

Medication / device: {{{{injectate_product}}}} Dose/volume/settings: {{{{dose_volume}}}} Medication mix/diluent: {{{{diluent_anesthetic}}}} Total delivered: {{{{total_volume}}}} Lot/expiry/device ID: {{{{lot_expiry}}}}

Outcome: {{{{immediate_response}}}} Complications/adverse event: {{{{complications}}}}

Disposition: {{{{post_procedure_instructions}}}} {{{{follow_up_plan}}}}"""


COMMON_PROCEDURE_FIELDS: list[dict[str, Any]] = [
    {"section": "Safety", "key": "consent_phrase", "label": "Consent discussion", "default_layer": "Global Default", "input_type": "textarea", "required": True, "options": "", "help": "Editable global consent language; add procedure-specific risks."},
    {"section": "Safety", "key": "timeout_phrase", "label": "Time-out and safety screen", "default_layer": "Global Default", "input_type": "textarea", "required": True, "options": "", "help": "No default should be trusted if actual safety screen differs."},
    {"section": "Safety", "key": "allergy_infection_anticoagulant_screen", "label": "Allergy / infection / anticoagulant / medication safety screen", "default_layer": "No Default", "input_type": "textarea", "required": True, "options": "", "help": "Manual-only patient-specific safety finding."},
    {"section": "Indication", "key": "diagnosis", "label": "Diagnosis / indication", "default_layer": "No Default", "input_type": "text", "required": True, "options": "", "help": "Manual-only patient-specific diagnosis."},
    {"section": "Indication", "key": "clinical_indication", "label": "Clinical indication and failed conservative therapy", "default_layer": "No Default", "input_type": "textarea", "required": True, "options": "", "help": "Manual-only rationale for this procedure."},
    {"section": "Indication", "key": "side", "label": "Laterality / side", "default_layer": "No Default", "input_type": "select", "required": True, "options": "Right;Left;Bilateral;Midline;N/A", "help": "Manual-only wrong-site safety field."},
    {"section": "Indication", "key": "baseline_pain_function", "label": "Baseline pain / function before procedure", "default_layer": "No Default", "input_type": "textarea", "required": True, "options": "", "help": "Manual-only baseline before intervention."},
    {"section": "Setup", "key": "patient_position", "label": "Patient position", "default_layer": "Per-Form Default", "input_type": "text", "required": True, "options": "", "help": "Procedure-specific default; edit if changed."},
    {"section": "Setup", "key": "skin_prep", "label": "Skin preparation", "default_layer": "Global Default", "input_type": "text", "required": True, "options": "", "help": "Global default with allergy override."},
    {"section": "Setup", "key": "sterile_setup", "label": "Sterile setup", "default_layer": "Global Default", "input_type": "textarea", "required": True, "options": "", "help": "Global sterile technique text."},
    {"section": "Setup", "key": "monitoring", "label": "Monitoring", "default_layer": "Global Default", "input_type": "textarea", "required": True, "options": "", "help": "Select monitoring appropriate to injection, ablation, or stimulation."},
    {"section": "Guidance", "key": "guidance", "label": "Guidance modality", "default_layer": "Per-Form Default", "input_type": "text", "required": True, "options": "", "help": "Procedure-specific imaging or landmark technique."},
    {"section": "Guidance", "key": "guidance_phrase", "label": "Guidance documentation phrase", "default_layer": "Per-Form Default", "input_type": "textarea", "required": True, "options": "", "help": "Edit to match ultrasound, fluoroscopy, or landmark technique actually used."},
    {"section": "Guidance", "key": "image_saved", "label": "Images saved / archive location", "default_layer": "No Default", "input_type": "text", "required": True, "options": "", "help": "Manual-only: document if images saved and where."},
    {"section": "Technique", "key": "transducer_or_equipment", "label": "Transducer / equipment", "default_layer": "Per-Form Default", "input_type": "text", "required": True, "options": "", "help": "Probe/equipment used for the selected technique."},
    {"section": "Technique", "key": "approach", "label": "Needle approach", "default_layer": "Per-Form Default", "input_type": "text", "required": True, "options": "", "help": "Unique to procedure; edit if changed."},
    {"section": "Technique", "key": "target", "label": "Needle target", "default_layer": "Per-Form Default", "input_type": "text", "required": True, "options": "", "help": "Unique target for procedure/product type."},
    {"section": "Technique", "key": "needle", "label": "Needle / cannula / device", "default_layer": "Per-Form Default", "input_type": "text", "required": True, "options": "", "help": "Procedure-specific default; edit if changed."},
    {"section": "Technique", "key": "levels_targets", "label": "Levels / target sites treated", "default_layer": "No Default", "input_type": "text", "required": True, "options": "", "help": "Manual-only levels, side, or target sites."},
    {"section": "Technique", "key": "needle_visualization", "label": "Needle visualization / path / endpoint confirmation", "default_layer": "No Default", "input_type": "textarea", "required": True, "options": "", "help": "Manual-only actual visualization and safety observations."},
    {"section": "Technique", "key": "aspiration_result", "label": "Aspiration / stimulation / safety check", "default_layer": "No Default", "input_type": "text", "required": True, "options": "Negative;Positive;Not applicable", "help": "Manual-only actual finding."},
    {"section": "Technique", "key": "injection_character", "label": "Injection character / spread / resistance / response", "default_layer": "No Default", "input_type": "textarea", "required": True, "options": "", "help": "Manual-only actual spread/resistance/response."},
    {"section": "Injectate/Product", "key": "injectate_product", "label": "Medication / product / device", "default_layer": "Per-Form Default", "input_type": "text", "required": True, "options": "", "help": "Verify product, route appropriateness, DIN/device status, concentration, and patient-specific dose."},
    {"section": "Injectate/Product", "key": "dose_volume", "label": "Dose / volume / settings", "default_layer": "Per-Form Default", "input_type": "text", "required": True, "options": "", "help": "Visible physician-reviewed dose, volume, or device settings."},
    {"section": "Injectate/Product", "key": "diluent_anesthetic", "label": "Medication mix / diluent / local anesthetic", "default_layer": "Per-Form Default", "input_type": "text", "required": False, "options": "", "help": "Medication mix should be selected/edited for the encounter."},
    {"section": "Injectate/Product", "key": "total_volume", "label": "Total volume / total treatment delivered", "default_layer": "No Default", "input_type": "text", "required": True, "options": "", "help": "Manual-only actual total volume/treatment."},
    {"section": "Injectate/Product", "key": "lot_expiry", "label": "Lot / expiry / device identifiers", "default_layer": "No Default", "input_type": "text", "required": True, "options": "", "help": "Manual-only product/device tracking if required by clinic policy."},
    {"section": "Outcome", "key": "immediate_response", "label": "Immediate response / pain score change", "default_layer": "No Default", "input_type": "textarea", "required": True, "options": "", "help": "Manual-only actual response."},
    {"section": "Outcome", "key": "complications", "label": "Complications / adverse event", "default_layer": "No Default", "input_type": "textarea", "required": True, "options": "None;Vasovagal;Bleeding;Paresthesia;Other", "help": "Manual-only actual complications."},
    {"section": "Disposition", "key": "post_procedure_instructions", "label": "Post-procedure instructions", "default_layer": "Global Default", "input_type": "textarea", "required": True, "options": "", "help": "Global default; edit for procedure-specific warnings."},
    {"section": "Disposition", "key": "follow_up_plan", "label": "Follow-up plan", "default_layer": "Global Default", "input_type": "textarea", "required": True, "options": "", "help": "Global default; edit according to treatment plan."},
]


MISSING_PROCEDURE_SPECS: list[dict[str, Any]] = [
    {"form_id": "plantar_fascia_steroid_us", "title": "Plantar fascia corticosteroid injection - ultrasound-guided", "condition_ids": ["plantar_fasciopathy"], "conditions": ["Plantar fasciopathy", "Heel pain"], "region": "Foot / ankle", "guidance": "Ultrasound-guided", "intervention_type": "Injection", "procedure_group": "Plantar fascia injections", "target": "Plantar fascia origin/perifascial target region", "approach": "Medial in-plane approach avoiding plantar fat pad", "needle": "Echogenic needle selected by proceduralist", "injectate_product": "Corticosteroid with/without local anesthetic as selected; verify product and DIN", "dose_volume": "Small-volume steroid/local anesthetic injectate", "patient_position": "Supine or prone with foot positioned to expose medial heel"},
    {"form_id": "plantar_fascia_prp_us", "title": "Plantar fascia PRP injection / fenestration - ultrasound-guided", "condition_ids": ["plantar_fasciopathy"], "conditions": ["Plantar fasciopathy", "Heel pain"], "region": "Foot / ankle", "guidance": "Ultrasound-guided", "intervention_type": "Regenerative injection", "procedure_group": "Plantar fascia injections", "target": "Degenerative plantar fascia origin / perifascial target", "approach": "Medial in-plane approach with fenestration as selected", "needle": "Echogenic needle selected by proceduralist", "injectate_product": "Autologous PRP prepared using clinic-verified system", "dose_volume": "PRP volume/yield documented from current preparation", "patient_position": "Supine or prone with foot positioned to expose medial heel"},
    {"form_id": "plantar_fascia_prolo_us", "title": "Plantar fascia prolotherapy - ultrasound-guided or landmark-guided", "condition_ids": ["plantar_fasciopathy"], "conditions": ["Plantar fasciopathy", "Heel pain"], "region": "Foot / ankle", "guidance": "Ultrasound-guided where indicated; landmark-guided for superficial enthesis targeting as appropriate", "intervention_type": "Regenerative injection", "procedure_group": "Plantar fascia injections", "target": "Plantar fascia origin/enthesis and tender perifascial points", "approach": "Medial approach with enthesis/perifascial targeting", "needle": "Needle selected by proceduralist", "injectate_product": "Dextrose prolotherapy solution/local anesthetic mix per clinic protocol; verify products", "dose_volume": "Concentration and volume documented by site", "patient_position": "Supine or prone with foot positioned to expose medial heel"},
    {"form_id": "ilioinguinal_iliohypogastric_block_us", "title": "Ilioinguinal / iliohypogastric nerve block - ultrasound-guided", "condition_ids": ["ilioinguinal_neuralgia", "chronic_post_surgical_pain"], "conditions": ["Ilioinguinal neuralgia", "Iliohypogastric neuralgia", "Post-herniorrhaphy pain"], "region": "Abdomen / pelvis", "guidance": "Ultrasound-guided", "intervention_type": "Peripheral nerve block", "procedure_group": "Abdominal wall nerve blocks", "target": "Fascial plane between internal oblique and transversus abdominis containing ilioinguinal/iliohypogastric nerves", "approach": "In-plane approach in lower abdominal wall", "needle": "Echogenic block needle selected by proceduralist", "injectate_product": "Local anesthetic with/without steroid as selected; verify products/DIN", "dose_volume": "Volume/concentration selected within safety limits", "patient_position": "Supine with lower abdomen exposed"},
    {"form_id": "genitofemoral_block_us", "title": "Genitofemoral nerve block - ultrasound-guided", "condition_ids": ["ilioinguinal_neuralgia", "chronic_post_surgical_pain"], "conditions": ["Genitofemoral neuralgia", "Groin neuralgia", "Post-surgical groin pain"], "region": "Abdomen / pelvis", "guidance": "Ultrasound-guided", "intervention_type": "Peripheral nerve block", "procedure_group": "Abdominal wall nerve blocks", "target": "Genitofemoral nerve target region according to branch/site selected", "approach": "Ultrasound-guided branch-specific approach", "needle": "Echogenic block needle selected by proceduralist", "injectate_product": "Local anesthetic with/without steroid as selected; verify products/DIN", "dose_volume": "Small-volume perineural injectate selected by physician", "patient_position": "Supine with target region exposed"},
    {"form_id": "lateral_femoral_cutaneous_block_us", "title": "Lateral femoral cutaneous nerve block - ultrasound-guided", "condition_ids": ["peripheral_neuropathic_pain"], "conditions": ["Meralgia paresthetica", "Lateral femoral cutaneous neuralgia"], "region": "Hip / thigh", "guidance": "Ultrasound-guided", "intervention_type": "Peripheral nerve block", "procedure_group": "Lower limb peripheral nerve blocks", "target": "Lateral femoral cutaneous nerve near ASIS/inguinal ligament region", "approach": "In-plane approach around nerve target", "needle": "Echogenic block needle selected by proceduralist", "injectate_product": "Local anesthetic with/without steroid as selected; verify products/DIN", "dose_volume": "Low-volume perineural injectate", "patient_position": "Supine"},
    {"form_id": "saphenous_adductor_canal_block_us", "title": "Saphenous nerve / adductor canal block - ultrasound-guided", "condition_ids": ["knee_osteoarthritis", "peripheral_neuropathic_pain"], "conditions": ["Medial knee pain", "Saphenous neuralgia", "Chronic knee pain"], "region": "Knee / thigh", "guidance": "Ultrasound-guided", "intervention_type": "Peripheral nerve block", "procedure_group": "Lower limb peripheral nerve blocks", "target": "Saphenous nerve/adductor canal target region", "approach": "In-plane approach to adductor canal/saphenous nerve region", "needle": "Echogenic block needle selected by proceduralist", "injectate_product": "Local anesthetic with/without steroid as selected; verify products/DIN", "dose_volume": "Volume/concentration selected within safety limits", "patient_position": "Supine"},
    {"form_id": "peroneal_nerve_block_us", "title": "Common peroneal nerve block - ultrasound-guided", "condition_ids": ["peripheral_neuropathic_pain"], "conditions": ["Peroneal neuralgia", "Lateral leg neuropathic pain"], "region": "Knee / leg", "guidance": "Ultrasound-guided", "intervention_type": "Peripheral nerve block", "procedure_group": "Lower limb peripheral nerve blocks", "target": "Common peroneal nerve target region near fibular head or selected site", "approach": "In-plane perineural approach avoiding intraneural injection", "needle": "Echogenic block needle selected by proceduralist", "injectate_product": "Local anesthetic with/without steroid as selected; verify products/DIN", "dose_volume": "Low-volume perineural injectate", "patient_position": "Supine or lateral"},
    {"form_id": "tibial_nerve_block_us", "title": "Posterior tibial nerve block - ultrasound-guided", "condition_ids": ["peripheral_neuropathic_pain", "mortons_neuroma"], "conditions": ["Tibial neuralgia", "Tarsal tunnel syndrome", "Foot neuropathic pain"], "region": "Foot / ankle", "guidance": "Ultrasound-guided", "intervention_type": "Peripheral nerve block", "procedure_group": "Lower limb peripheral nerve blocks", "target": "Posterior tibial nerve target region", "approach": "In-plane perineural approach avoiding intraneural injection", "needle": "Echogenic block needle selected by proceduralist", "injectate_product": "Local anesthetic with/without steroid as selected; verify products/DIN", "dose_volume": "Low-volume perineural injectate", "patient_position": "Supine or prone with medial ankle accessible"},
    {"form_id": "hip_ha_us", "title": "Hip intra-articular hyaluronic acid injection - ultrasound-guided", "condition_ids": ["hip_osteoarthritis"], "conditions": ["Hip osteoarthritis", "Chronic groin pain"], "region": "Hip / pelvis", "guidance": "Ultrasound-guided, in-plane", "intervention_type": "Viscosupplementation", "procedure_group": "Hip joint injections", "target": "Femoral head-neck junction / anterior hip joint recess", "approach": "Anterior oblique in-plane approach", "needle": "Spinal or echogenic needle sized to depth", "injectate_product": "Hyaluronic acid product selected by physician; verify device/licence/product details", "dose_volume": "Product-specific volume/dose", "patient_position": "Supine"},
    {"form_id": "hip_periarticular_prolo_us", "title": "Hip periarticular / capsular-ligament prolotherapy - ultrasound-guided", "condition_ids": ["hip_osteoarthritis", "gtps"], "conditions": ["Hip osteoarthritis", "Periarticular hip pain"], "region": "Hip / pelvis", "guidance": "Ultrasound-guided where indicated plus palpation-guided superficial enthesis targeting as appropriate", "intervention_type": "Regenerative injection", "procedure_group": "Hip periarticular injections", "target": "Hip capsular/ligamentous/enthesis targets selected by physician", "approach": "Site-specific approach to tender/sonographic targets", "needle": "Needle selected by proceduralist", "injectate_product": "Dextrose prolotherapy solution/local anesthetic mix per clinic protocol; verify products", "dose_volume": "Concentration and volume documented by site", "patient_position": "Supine or lateral depending on targets"},
    {"form_id": "greater_trochanter_prp_us", "title": "Greater trochanteric / gluteal tendon PRP injection - ultrasound-guided", "condition_ids": ["gtps"], "conditions": ["Greater trochanteric pain syndrome", "Gluteal tendinopathy"], "region": "Hip / pelvis", "guidance": "Ultrasound-guided", "intervention_type": "Regenerative injection", "procedure_group": "Hip periarticular injections", "target": "Gluteal tendon/peritendinous target and/or trochanteric bursa region", "approach": "In-plane lateral approach", "needle": "Echogenic needle selected by proceduralist", "injectate_product": "Autologous PRP prepared using clinic-verified system", "dose_volume": "PRP volume/yield documented from current preparation", "patient_position": "Lateral decubitus or side-lying"},
    {"form_id": "biceps_tendon_sheath_steroid_us", "title": "Long head biceps tendon sheath corticosteroid injection - ultrasound-guided", "condition_ids": ["biceps_tendinopathy", "rotator_cuff_subacromial"], "conditions": ["Long head biceps tendinopathy", "Anterior shoulder pain"], "region": "Shoulder", "guidance": "Ultrasound-guided, in-plane", "intervention_type": "Injection", "procedure_group": "Shoulder tendon/bursa injections", "target": "Long head biceps tendon sheath in bicipital groove", "approach": "In-plane approach to tendon sheath avoiding intratendinous injection", "needle": "Echogenic needle selected by proceduralist", "injectate_product": "Corticosteroid with/without local anesthetic as selected; verify product and DIN", "dose_volume": "Small-volume tendon sheath injectate", "patient_position": "Supine or seated with shoulder positioned to expose bicipital groove"},
    {"form_id": "shoulder_ha_us", "title": "Shoulder glenohumeral hyaluronic acid injection - ultrasound-guided", "condition_ids": ["shoulder_oa_capsulitis"], "conditions": ["Shoulder osteoarthritis", "Adhesive capsulitis"], "region": "Shoulder", "guidance": "Ultrasound-guided, in-plane", "intervention_type": "Viscosupplementation", "procedure_group": "Shoulder joint injections", "target": "Glenohumeral joint recess", "approach": "Posterior or anterior in-plane approach as selected", "needle": "Spinal or echogenic needle selected by proceduralist", "injectate_product": "Hyaluronic acid product selected by physician; verify device/licence/product details", "dose_volume": "Product-specific volume/dose", "patient_position": "Seated or lateral/prone according to approach"},
    {"form_id": "ankle_prp_us", "title": "Tibiotalar ankle joint PRP injection - ultrasound-guided", "condition_ids": ["ankle_osteoarthritis"], "conditions": ["Ankle osteoarthritis", "Chronic ankle pain"], "region": "Foot / ankle", "guidance": "Ultrasound-guided", "intervention_type": "Regenerative injection", "procedure_group": "Ankle joint injections", "target": "Tibiotalar joint recess", "approach": "Anterior in-plane or out-of-plane approach according to anatomy", "needle": "Echogenic needle selected by proceduralist", "injectate_product": "Autologous PRP prepared using clinic-verified system", "dose_volume": "PRP volume/yield documented from current preparation", "patient_position": "Supine with ankle accessible"},
    {"form_id": "coccygeal_ligament_injection_us", "title": "Coccygeal ligament / sacrococcygeal injection - ultrasound-guided or landmark-guided", "condition_ids": ["coccydynia"], "conditions": ["Coccydynia", "Sacrococcygeal pain"], "region": "Pelvis / coccyx", "guidance": "Ultrasound-guided or landmark-guided according to anatomy and target depth", "intervention_type": "Injection", "procedure_group": "Coccyx / ganglion impar region", "target": "Sacrococcygeal joint/ligament or tender coccygeal target", "approach": "Midline or paramedian approach to selected coccygeal target", "needle": "Needle selected by proceduralist", "injectate_product": "Local anesthetic with/without steroid as selected; verify products/DIN", "dose_volume": "Small-volume injectate by target", "patient_position": "Prone or lateral with coccyx accessible"},
    {"form_id": "lumbar_interlaminar_esi_us", "title": "Lumbar interlaminar epidural steroid injection - ultrasound-assisted / no fluoroscopy", "condition_ids": ["lumbar_radiculopathy"], "conditions": ["Lumbar radicular pain", "Sciatica", "Lumbar spinal stenosis"], "region": "Lumbar spine", "guidance": "Ultrasound-assisted; no fluoroscopy", "intervention_type": "Injection", "procedure_group": "Epidural steroid injections (ESI)", "target": "Lumbar epidural space via interlaminar access at documented level", "approach": "Midline or paramedian interlaminar approach", "needle": "Tuohy epidural needle sized to patient habitus and target depth", "injectate_product": "Steroid and preservative-free saline/local anesthetic mix selected by physician; verify route/product/DIN", "dose_volume": "Physician-selected epidural steroid dose and volume", "patient_position": "Sitting or lateral decubitus with lumbar flexion"},
    {"form_id": "caudal_esi_us", "title": "Caudal epidural steroid injection - ultrasound-guided / no fluoroscopy", "condition_ids": ["lumbar_radiculopathy"], "conditions": ["Lumbar radicular pain", "Sciatica", "Lumbar spinal stenosis"], "region": "Lumbar spine", "guidance": "Ultrasound-guided; no fluoroscopy", "intervention_type": "Injection", "procedure_group": "Epidural steroid injections (ESI)", "target": "Caudal epidural space through sacrococcygeal ligament", "approach": "Midline caudal approach through sacral hiatus", "needle": "22G spinal needle or epidural needle according to depth and protocol", "injectate_product": "Epidural steroid injectate selected by physician; verify route/product/DIN", "dose_volume": "Physician-selected epidural steroid dose/volume", "patient_position": "Prone with sacral hiatus accessible"},
    {"form_id": "lumbar_selective_nerve_root_block_us", "title": "Lumbar selective nerve root / periradicular injection - ultrasound-guided", "condition_ids": ["lumbar_radiculopathy"], "conditions": ["Lumbar radicular pain", "Sciatica"], "region": "Lumbar spine", "guidance": "Ultrasound-guided; no fluoroscopic contrast confirmation", "intervention_type": "Injection", "procedure_group": "Selective nerve root blocks (SNRB)", "target": "Periradicular region adjacent to selected lumbar nerve root/foramen as visualized by ultrasound landmarks", "approach": "Oblique in-plane approach toward documented periradicular/foraminal region", "needle": "Spinal or echogenic block needle selected for depth and body habitus", "injectate_product": "Local anesthetic with/without steroid as selected; verify route/product/DIN", "dose_volume": "Low-volume injectate selected per target", "patient_position": "Prone or lateral position according to target level and tolerance"},
    {"form_id": "lumbar_facet_mbb_us", "title": "Lumbar medial branch block - ultrasound-guided", "condition_ids": ["lumbar_facet_pain"], "conditions": ["Lumbar facet-mediated pain", "Axial low back pain"], "region": "Lumbar spine", "guidance": "Ultrasound-guided", "intervention_type": "Injection", "procedure_group": "Facet / medial branch blocks", "target": "Lumbar medial branch target region or L5 dorsal ramus target as documented", "approach": "Posterior oblique in-plane or out-of-plane approach according to level and visualization", "needle": "Spinal or echogenic needle sized to target depth", "injectate_product": "Local anesthetic diagnostic block injectate", "dose_volume": "Low-volume local anesthetic per target", "patient_position": "Prone with abdomen supported as needed"},
    {"form_id": "lumbar_paravertebral_block_us", "title": "Lumbar paravertebral block - ultrasound-guided", "condition_ids": ["lumbar_radiculopathy", "lumbar_facet_pain"], "conditions": ["Lumbar pain", "Postsurgical lumbar pain"], "region": "Lumbar spine", "guidance": "Ultrasound-guided", "intervention_type": "Regional block", "procedure_group": "Regional anesthesia / fascial plane blocks", "target": "Lumbar paravertebral region at documented level(s)", "approach": "In-plane approach to selected lumbar paravertebral region", "needle": "Echogenic block needle selected by proceduralist", "injectate_product": "Local anesthetic with/without adjunct as selected; verify products/DIN", "dose_volume": "Volume/concentration selected within safety limits", "patient_position": "Prone, lateral, or sitting according to level and tolerance"},
    {"form_id": "tlip_block_us", "title": "Thoracolumbar interfascial plane (TLIP) block - ultrasound-guided", "condition_ids": ["lumbar_radiculopathy", "lumbar_facet_pain", "myofascial_pain"], "conditions": ["Lumbar pain", "Postsurgical lumbar pain", "Myofascial lumbar pain"], "region": "Lumbar spine", "guidance": "Ultrasound-guided", "intervention_type": "Regional block", "procedure_group": "Regional anesthesia / fascial plane blocks", "target": "Thoracolumbar interfascial plane at documented level(s)", "approach": "In-plane approach between multifidus and longissimus or modified TLIP plane as selected", "needle": "Echogenic block needle selected by proceduralist", "injectate_product": "Local anesthetic with/without adjunct as selected; verify products/DIN", "dose_volume": "Volume/concentration selected within safety limits", "patient_position": "Prone or lateral with lumbar paraspinal region accessible"},
]


ADVANCED_PAIN_PROCEDURE_SPECS: list[dict[str, Any]] = [
    {"form_id": "cervical_selective_nerve_root_block_us", "title": "Cervical selective nerve root / periradicular injection - ultrasound-guided", "condition_ids": ["cervical_radiculopathy"], "conditions": ["Cervical radicular pain"], "region": "Cervical spine / head", "guidance": "Ultrasound-guided; no fluoroscopic contrast confirmation", "intervention_type": "Injection", "procedure_group": "Selective nerve root blocks (SNRB)", "target": "Cervical nerve root/periradicular target region at documented level", "approach": "Lateral/anterolateral ultrasound-guided approach according to anatomy and safety", "needle": "Echogenic needle selected by proceduralist", "injectate_product": "Local anesthetic with/without steroid as selected; verify route/product/DIN", "dose_volume": "Low-volume injectate selected per target", "patient_position": "Supine or lateral with cervical region exposed"},
    {"form_id": "cervical_mbb_us", "title": "Cervical medial branch block - ultrasound-guided", "condition_ids": ["cervical_facet_pain", "occipital_neuralgia"], "conditions": ["Cervical facet-mediated pain", "Cervicogenic headache"], "region": "Cervical spine / head", "guidance": "Ultrasound-guided", "intervention_type": "Injection", "procedure_group": "Facet / medial branch blocks", "target": "Cervical medial branch target region at documented level(s)", "approach": "In-plane or out-of-plane approach according to level and visualization", "needle": "Echogenic needle selected by proceduralist", "injectate_product": "Local anesthetic diagnostic block injectate", "dose_volume": "Low-volume local anesthetic per target", "patient_position": "Lateral, prone, or seated according to target and tolerance"},
    {"form_id": "cervical_third_occipital_nerve_block_us", "title": "Third occipital nerve block - ultrasound-guided", "condition_ids": ["occipital_neuralgia", "cervical_facet_pain"], "conditions": ["Cervicogenic headache", "Third occipital neuralgia"], "region": "Cervical spine / head", "guidance": "Ultrasound-guided", "intervention_type": "Peripheral nerve block", "procedure_group": "Headache / occipital procedures", "target": "Third occipital nerve/C2-3 facet target region", "approach": "Ultrasound-guided approach according to anatomy", "needle": "Echogenic needle selected by proceduralist", "injectate_product": "Local anesthetic with/without steroid as selected; verify products/DIN", "dose_volume": "Low-volume injectate", "patient_position": "Prone, lateral, or seated"},
    {"form_id": "occipital_nerve_prf_us", "title": "Greater / lesser occipital nerve pulsed radiofrequency - ultrasound-guided", "condition_ids": ["occipital_neuralgia"], "conditions": ["Occipital neuralgia", "Cervicogenic headache"], "region": "Cervical spine / head", "guidance": "Ultrasound-guided", "intervention_type": "Ablation / PRF", "procedure_group": "Headache / occipital procedures", "target": "Greater and/or lesser occipital nerve target as documented", "approach": "Ultrasound-guided perineural RF cannula placement", "needle": "RF cannula/electrode selected by proceduralist", "injectate_product": "Pulsed RF treatment; local anesthetic as selected", "dose_volume": "PRF settings, duration, sensory testing, and local anesthetic volume documented", "patient_position": "Prone, lateral, or seated"},
    {"form_id": "supratrochlear_supraorbital_block_us", "title": "Supraorbital / supratrochlear nerve block - ultrasound-guided or landmark-guided", "condition_ids": ["occipital_neuralgia", "peripheral_neuropathic_pain"], "conditions": ["Frontal neuralgia", "Headache neuralgia"], "region": "Cervical spine / head", "guidance": "Ultrasound-guided or landmark-guided according to target and anatomy", "intervention_type": "Peripheral nerve block", "procedure_group": "Headache / cranial nerve blocks", "target": "Supraorbital and/or supratrochlear nerve region", "approach": "Superficial perineural approach avoiding vascular structures", "needle": "Small-gauge needle selected by proceduralist", "injectate_product": "Local anesthetic with/without steroid as selected; verify products/DIN", "dose_volume": "Small-volume superficial nerve block injectate", "patient_position": "Supine or seated"},
    {"form_id": "auriculotemporal_block_us", "title": "Auriculotemporal nerve block - ultrasound-guided or landmark-guided", "condition_ids": ["peripheral_neuropathic_pain"], "conditions": ["Auriculotemporal neuralgia", "Temporal headache neuralgia"], "region": "Cervical spine / head", "guidance": "Ultrasound-guided or landmark-guided according to target and anatomy", "intervention_type": "Peripheral nerve block", "procedure_group": "Headache / cranial nerve blocks", "target": "Auriculotemporal nerve region", "approach": "Superficial perineural approach avoiding temporal vessels", "needle": "Small-gauge needle selected by proceduralist", "injectate_product": "Local anesthetic with/without steroid as selected; verify products/DIN", "dose_volume": "Small-volume superficial nerve block injectate", "patient_position": "Supine or seated"},
    {"form_id": "trigeminal_branch_block_us", "title": "Peripheral trigeminal branch block - ultrasound-guided or landmark-guided", "condition_ids": ["peripheral_neuropathic_pain"], "conditions": ["Trigeminal branch neuralgia", "Facial neuropathic pain"], "region": "Cervical spine / head", "guidance": "Ultrasound-guided or landmark-guided according to branch and anatomy", "intervention_type": "Peripheral nerve block", "procedure_group": "Headache / cranial nerve blocks", "target": "Selected trigeminal branch target region", "approach": "Branch-specific superficial perineural approach", "needle": "Small-gauge needle selected by proceduralist", "injectate_product": "Local anesthetic with/without steroid as selected; verify products/DIN", "dose_volume": "Small-volume superficial nerve block injectate", "patient_position": "Supine or seated"},
    {"form_id": "thoracic_paravertebral_block_us", "title": "Thoracic paravertebral block - ultrasound-guided", "condition_ids": ["thoracic_facet_rib_pain", "intercostal_neuralgia", "chronic_post_surgical_pain"], "conditions": ["Thoracic pain", "Intercostal neuralgia", "Post-thoracotomy pain"], "region": "Thoracic spine / chest wall", "guidance": "Ultrasound-guided", "intervention_type": "Regional block", "procedure_group": "Regional anesthesia / fascial plane blocks", "target": "Thoracic paravertebral region at documented level(s)", "approach": "In-plane ultrasound-guided approach according to anatomy", "needle": "Echogenic block needle selected by proceduralist", "injectate_product": "Local anesthetic with/without adjunct as selected; verify products/DIN", "dose_volume": "Volume/concentration selected within safety limits", "patient_position": "Sitting, lateral, or prone"},
    {"form_id": "serratus_anterior_plane_block_us", "title": "Serratus anterior plane block - ultrasound-guided", "condition_ids": ["intercostal_neuralgia", "thoracic_facet_rib_pain", "chronic_post_surgical_pain"], "conditions": ["Lateral chest wall pain", "Post-thoracotomy pain"], "region": "Thoracic spine / chest wall", "guidance": "Ultrasound-guided", "intervention_type": "Regional block", "procedure_group": "Regional anesthesia / fascial plane blocks", "target": "Serratus anterior fascial plane at selected rib level", "approach": "In-plane lateral thoracic wall approach", "needle": "Echogenic block needle selected by proceduralist", "injectate_product": "Local anesthetic with/without adjunct as selected; verify products/DIN", "dose_volume": "Volume/concentration selected within safety limits", "patient_position": "Supine, lateral, or seated"},
    {"form_id": "pecs_block_us", "title": "PECS I / PECS II block - ultrasound-guided", "condition_ids": ["chronic_post_surgical_pain", "intercostal_neuralgia"], "conditions": ["Anterior chest wall pain", "Post-breast surgery pain"], "region": "Thoracic spine / chest wall", "guidance": "Ultrasound-guided", "intervention_type": "Regional block", "procedure_group": "Regional anesthesia / fascial plane blocks", "target": "Pectoral fascial plane(s) selected by physician", "approach": "In-plane anterior chest wall approach", "needle": "Echogenic block needle selected by proceduralist", "injectate_product": "Local anesthetic with/without adjunct as selected; verify products/DIN", "dose_volume": "Volume/concentration selected within safety limits", "patient_position": "Supine"},
    {"form_id": "rhomboid_intercostal_plane_block_us", "title": "Rhomboid intercostal / subserratus plane block - ultrasound-guided", "condition_ids": ["thoracic_facet_rib_pain", "intercostal_neuralgia", "chronic_post_surgical_pain"], "conditions": ["Posterior thoracic pain", "Scapulothoracic pain"], "region": "Thoracic spine / chest wall", "guidance": "Ultrasound-guided", "intervention_type": "Regional block", "procedure_group": "Regional anesthesia / fascial plane blocks", "target": "Rhomboid intercostal and/or subserratus fascial plane", "approach": "In-plane posterior thoracic wall approach", "needle": "Echogenic block needle selected by proceduralist", "injectate_product": "Local anesthetic with/without adjunct as selected; verify products/DIN", "dose_volume": "Volume/concentration selected within safety limits", "patient_position": "Sitting, prone, or lateral"},
    {"form_id": "ganglion_impar_us", "title": "Ganglion impar block - ultrasound-guided or landmark-assisted", "condition_ids": ["coccydynia", "pudendal_neuralgia"], "conditions": ["Coccydynia", "Perineal pain", "Pelvic pain"], "region": "Pelvis / sacroiliac / hip", "guidance": "Ultrasound-guided or landmark-assisted according to anatomy; fluoroscopy option remains separate", "intervention_type": "Sympathetic block", "procedure_group": "Pelvic / sympathetic blocks", "target": "Ganglion impar / sacrococcygeal target region", "approach": "Trans-sacrococcygeal or intercoccygeal approach according to anatomy", "needle": "Spinal needle selected by proceduralist", "injectate_product": "Local anesthetic with/without steroid as selected; verify products/DIN", "dose_volume": "Small-volume injectate selected by physician", "patient_position": "Prone or lateral"},
    {"form_id": "superior_hypogastric_plexus_block_us", "title": "Superior hypogastric plexus block - ultrasound-guided or image-guided", "condition_ids": ["pudendal_neuralgia", "chronic_post_surgical_pain"], "conditions": ["Chronic pelvic pain", "Visceral pelvic pain"], "region": "Pelvis / sacroiliac / hip", "guidance": "Ultrasound-guided or other image-guided technique according to anatomy and protocol", "intervention_type": "Sympathetic block", "procedure_group": "Pelvic / sympathetic blocks", "target": "Superior hypogastric plexus target region", "approach": "Anterior or posterior image-guided approach according to protocol", "needle": "Needle selected by proceduralist", "injectate_product": "Local anesthetic with/without steroid as selected; verify products/DIN", "dose_volume": "Volume/concentration selected by physician", "patient_position": "Supine, prone, or oblique according to approach"},
    {"form_id": "stellate_ganglion_block_us", "title": "Stellate ganglion block - ultrasound-guided", "condition_ids": ["crps", "peripheral_neuropathic_pain"], "conditions": ["Upper limb CRPS", "Sympathetically maintained pain", "Facial/upper extremity neuropathic pain"], "region": "Cervical spine / head", "guidance": "Ultrasound-guided", "intervention_type": "Sympathetic block", "procedure_group": "Sympathetic blocks", "target": "Cervical sympathetic chain / stellate ganglion target region", "approach": "Anterior lateral ultrasound-guided approach with vascular, thyroid, esophagus, and pleura avoidance", "needle": "Echogenic block needle selected by proceduralist", "injectate_product": "Local anesthetic with/without adjunct as selected; verify dose and contraindications", "dose_volume": "Low-volume local anesthetic injectate within safety limits", "patient_position": "Supine with neck slightly extended and turned as tolerated"},
    {"form_id": "lumbar_sympathetic_block_us", "title": "Lumbar sympathetic block - ultrasound-guided or image-guided", "condition_ids": ["crps", "peripheral_neuropathic_pain"], "conditions": ["Lower limb CRPS", "Sympathetically maintained lower limb pain"], "region": "Lumbar spine", "guidance": "Ultrasound-guided where feasible or other image-guided technique according to anatomy/protocol", "intervention_type": "Sympathetic block", "procedure_group": "Sympathetic blocks", "target": "Lumbar sympathetic chain target region", "approach": "Posterolateral target-specific approach with vascular/visceral avoidance", "needle": "Spinal or block needle selected by proceduralist", "injectate_product": "Local anesthetic with/without adjunct as selected; verify dose and contraindications", "dose_volume": "Volume/concentration selected by physician and documented", "patient_position": "Prone or lateral according to approach"},
    {"form_id": "erector_spinae_plane_block_us", "title": "Erector spinae plane block - ultrasound-guided", "condition_ids": ["thoracic_facet_rib_pain", "intercostal_neuralgia", "chronic_post_surgical_pain", "lumbar_facet_pain"], "conditions": ["Thoracic pain", "Rib/chest wall pain", "Lumbar myofascial or regional pain"], "region": "Thoracic spine / ribs", "guidance": "Ultrasound-guided", "intervention_type": "Regional block", "procedure_group": "Regional anesthesia / fascial plane blocks", "target": "Erector spinae fascial plane at selected vertebral level(s)", "approach": "In-plane approach to transverse process / fascial plane endpoint", "needle": "Echogenic block needle selected by proceduralist", "injectate_product": "Local anesthetic with/without steroid or adjunct as selected; verify dose", "dose_volume": "Plane block volume/concentration selected within safety limits", "patient_position": "Prone, lateral, or seated according to target level"},
    {"form_id": "quadratus_lumborum_block_us", "title": "Quadratus lumborum block - ultrasound-guided", "condition_ids": ["lumbar_facet_pain", "sacroiliac_joint_pain", "chronic_post_surgical_pain"], "conditions": ["Flank pain", "Low back / pelvic regional pain", "Post-surgical abdominal wall pain"], "region": "Lumbar spine", "guidance": "Ultrasound-guided", "intervention_type": "Regional block", "procedure_group": "Regional anesthesia / fascial plane blocks", "target": "Quadratus lumborum fascial plane target selected by approach", "approach": "Lateral, posterior, or transmuscular QL approach as selected", "needle": "Echogenic block needle selected by proceduralist", "injectate_product": "Local anesthetic with/without adjunct as selected; verify dose", "dose_volume": "Plane block volume/concentration selected within safety limits", "patient_position": "Lateral, prone, or supine according to approach"},
    {"form_id": "transversus_abdominis_plane_block_us", "title": "Transversus abdominis plane block - ultrasound-guided", "condition_ids": ["ilioinguinal_neuralgia", "chronic_post_surgical_pain"], "conditions": ["Abdominal wall pain", "Post-surgical abdominal wall pain", "Ilioinguinal/iliohypogastric distribution pain"], "region": "Abdomen / pelvis", "guidance": "Ultrasound-guided", "intervention_type": "Regional block", "procedure_group": "Regional anesthesia / fascial plane blocks", "target": "Plane between internal oblique and transversus abdominis", "approach": "In-plane lateral or subcostal TAP approach according to pain distribution", "needle": "Echogenic block needle selected by proceduralist", "injectate_product": "Local anesthetic with/without steroid or adjunct as selected; verify dose", "dose_volume": "Plane block volume/concentration selected within safety limits", "patient_position": "Supine"},
    {"form_id": "obturator_nerve_block_us", "title": "Obturator nerve block - ultrasound-guided", "condition_ids": ["hip_osteoarthritis", "peripheral_neuropathic_pain"], "conditions": ["Hip/groin pain", "Obturator neuralgia"], "region": "Pelvis / sacroiliac / hip", "guidance": "Ultrasound-guided", "intervention_type": "Peripheral nerve block", "procedure_group": "Pelvic / lower limb nerve blocks", "target": "Anterior/posterior obturator nerve branches or obturator nerve target region", "approach": "Ultrasound-guided adductor compartment approach", "needle": "Echogenic block needle selected by proceduralist", "injectate_product": "Local anesthetic with/without steroid as selected; verify products/DIN", "dose_volume": "Low-volume perineural injectate by branch/target", "patient_position": "Supine with hip externally rotated as tolerated"},
    {"form_id": "femoral_nerve_block_us", "title": "Femoral nerve block - ultrasound-guided", "condition_ids": ["hip_osteoarthritis", "knee_osteoarthritis", "peripheral_neuropathic_pain"], "conditions": ["Femoral neuralgia", "Anterior thigh pain", "Hip/knee pain"], "region": "Pelvis / sacroiliac / hip", "guidance": "Ultrasound-guided", "intervention_type": "Peripheral nerve block", "procedure_group": "Pelvic / lower limb nerve blocks", "target": "Femoral nerve target region", "approach": "In-plane inguinal approach avoiding vascular structures", "needle": "Echogenic block needle selected by proceduralist", "injectate_product": "Local anesthetic with/without steroid as selected; verify products/DIN", "dose_volume": "Volume/concentration selected within safety limits", "patient_position": "Supine"},
    {"form_id": "pengi_block_us", "title": "Pericapsular nerve group (PENG) block - ultrasound-guided", "condition_ids": ["hip_osteoarthritis"], "conditions": ["Hip osteoarthritis", "Chronic anterior hip pain"], "region": "Pelvis / sacroiliac / hip", "guidance": "Ultrasound-guided", "intervention_type": "Regional block", "procedure_group": "Hip articular nerve blocks", "target": "Plane between psoas tendon and pubic ramus / articular branch target region", "approach": "In-plane anterior approach", "needle": "Echogenic block needle selected by proceduralist", "injectate_product": "Local anesthetic with/without adjunct as selected; verify products/DIN", "dose_volume": "Volume/concentration selected within safety limits", "patient_position": "Supine"},
    {"form_id": "shoulder_articular_branch_block_us", "title": "Shoulder articular branch block - ultrasound-guided", "condition_ids": ["shoulder_oa_capsulitis", "rotator_cuff_subacromial"], "conditions": ["Chronic shoulder pain", "Glenohumeral osteoarthritis"], "region": "Shoulder", "guidance": "Ultrasound-guided", "intervention_type": "Peripheral nerve block", "procedure_group": "Shoulder nerve procedures", "target": "Selected suprascapular, axillary, lateral pectoral, or other shoulder articular branch target(s)", "approach": "Target-specific ultrasound-guided approach", "needle": "Echogenic needle selected by proceduralist", "injectate_product": "Local anesthetic diagnostic block injectate with/without steroid as selected", "dose_volume": "Low-volume injectate by target", "patient_position": "Seated, lateral, or prone according to target"},
    {"form_id": "shoulder_articular_branch_rfa", "title": "Shoulder articular branch radiofrequency ablation - image-guided", "condition_ids": ["shoulder_oa_capsulitis", "rotator_cuff_subacromial"], "conditions": ["Chronic shoulder pain", "Shoulder osteoarthritis"], "region": "Shoulder", "guidance": "Ultrasound-guided or fluoroscopy-guided according to target and protocol", "intervention_type": "Ablation / PRF", "procedure_group": "Shoulder nerve procedures", "target": "Selected shoulder articular sensory branch targets", "approach": "Target-specific image-guided RF cannula placement", "needle": "RF cannula/electrode selected by proceduralist", "injectate_product": "Radiofrequency treatment; local anesthetic/post-lesion injectate as selected", "dose_volume": "RF mode, temperature/duration or PRF settings, lesion count, and injectate volume documented", "patient_position": "Positioned according to selected target(s)"},
    {"form_id": "suprascapular_nerve_rfa_us", "title": "Suprascapular nerve pulsed radiofrequency / ablation - ultrasound-guided", "condition_ids": ["shoulder_oa_capsulitis", "rotator_cuff_subacromial"], "conditions": ["Chronic shoulder pain", "Suprascapular neuralgia"], "region": "Shoulder", "guidance": "Ultrasound-guided", "intervention_type": "Ablation / PRF", "procedure_group": "Shoulder nerve procedures", "target": "Suprascapular nerve target region", "approach": "Ultrasound-guided RF cannula placement near target nerve", "needle": "RF cannula/electrode selected by proceduralist", "injectate_product": "Pulsed RF or ablation treatment; local anesthetic as selected", "dose_volume": "PRF/RF settings, duration, sensory/motor testing, and injectate volume documented", "patient_position": "Seated, prone, or lateral"},
    {"form_id": "genicular_nerve_block_us", "title": "Genicular nerve diagnostic block - ultrasound-guided", "condition_ids": ["knee_osteoarthritis"], "conditions": ["Knee osteoarthritis", "Chronic knee pain"], "region": "Knee", "guidance": "Ultrasound-guided", "intervention_type": "Peripheral nerve block", "procedure_group": "Knee genicular procedures", "target": "Superior medial, superior lateral, inferior medial and/or additional genicular nerve targets as selected", "approach": "Target-specific in-plane or out-of-plane approach", "needle": "Echogenic needle selected by proceduralist", "injectate_product": "Local anesthetic diagnostic block injectate", "dose_volume": "Low-volume local anesthetic per target", "patient_position": "Supine with knee supported"},
    {"form_id": "genicular_prf_us", "title": "Genicular nerve pulsed radiofrequency - ultrasound-guided", "condition_ids": ["knee_osteoarthritis"], "conditions": ["Knee osteoarthritis", "Chronic knee pain"], "region": "Knee", "guidance": "Ultrasound-guided", "intervention_type": "Ablation / PRF", "procedure_group": "Knee genicular procedures", "target": "Selected genicular nerve targets", "approach": "Target-specific ultrasound-guided RF cannula placement", "needle": "RF cannula/electrode selected by proceduralist", "injectate_product": "Pulsed RF treatment; local anesthetic as selected", "dose_volume": "PRF settings, duration, sensory/motor testing, and injectate volume documented", "patient_position": "Supine with knee supported"},
    {"form_id": "hip_articular_branch_block_us", "title": "Hip articular branch diagnostic block - ultrasound-guided", "condition_ids": ["hip_osteoarthritis"], "conditions": ["Hip osteoarthritis", "Chronic hip/groin pain"], "region": "Pelvis / sacroiliac / hip", "guidance": "Ultrasound-guided", "intervention_type": "Peripheral nerve block", "procedure_group": "Hip articular nerve blocks", "target": "Femoral and/or obturator articular branch target region(s)", "approach": "Target-specific ultrasound-guided approach", "needle": "Echogenic needle selected by proceduralist", "injectate_product": "Local anesthetic diagnostic block injectate", "dose_volume": "Low-volume injectate by target", "patient_position": "Supine"},
    {"form_id": "hip_articular_branch_rfa", "title": "Hip articular branch radiofrequency ablation - image-guided", "condition_ids": ["hip_osteoarthritis"], "conditions": ["Hip osteoarthritis", "Chronic hip/groin pain"], "region": "Pelvis / sacroiliac / hip", "guidance": "Ultrasound-guided or fluoroscopy-guided according to target and protocol", "intervention_type": "Ablation / PRF", "procedure_group": "Hip articular nerve blocks", "target": "Femoral and/or obturator articular sensory branch targets", "approach": "Target-specific image-guided RF cannula placement", "needle": "RF cannula/electrode selected by proceduralist", "injectate_product": "Radiofrequency treatment; local anesthetic/post-lesion injectate as selected", "dose_volume": "RF settings, lesion count, and injectate volume documented", "patient_position": "Supine"},
    {"form_id": "peripheral_nerve_prf_us", "title": "Peripheral nerve pulsed radiofrequency - ultrasound-guided", "condition_ids": ["peripheral_neuropathic_pain", "chronic_post_surgical_pain", "cluneal_neuralgia", "ilioinguinal_neuralgia"], "conditions": ["Peripheral neuropathic pain", "Post-surgical neuralgia"], "region": "General / multisite pain", "guidance": "Ultrasound-guided", "intervention_type": "Ablation / PRF", "procedure_group": "Peripheral nerve stimulation / PRF", "target": "Selected peripheral nerve target documented by physician", "approach": "Target-specific ultrasound-guided RF cannula placement", "needle": "RF cannula/electrode selected by proceduralist", "injectate_product": "Pulsed RF treatment; local anesthetic as selected", "dose_volume": "PRF settings, duration, sensory/motor testing, and injectate volume documented", "patient_position": "Positioned according to target nerve"},
    {"form_id": "peripheral_nerve_stimulation_trial_us", "title": "Peripheral nerve stimulation trial lead placement - ultrasound-guided", "condition_ids": ["peripheral_neuropathic_pain", "chronic_post_surgical_pain", "cluneal_neuralgia", "knee_osteoarthritis", "shoulder_oa_capsulitis"], "conditions": ["Peripheral neuropathic pain", "Chronic post-surgical pain", "Chronic regional pain"], "region": "General / multisite pain", "guidance": "Ultrasound-guided and/or fluoroscopy-assisted according to target and device protocol", "intervention_type": "Stimulation / neuromodulation", "procedure_group": "Peripheral nerve stimulation / PRF", "target": "Selected peripheral nerve stimulation target documented by physician", "approach": "Device-specific percutaneous lead placement approach", "needle": "PNS introducer/lead system selected and verified", "injectate_product": "Peripheral nerve stimulation lead/device; local anesthetic as selected", "dose_volume": "Lead model, stimulation program, local anesthetic volume, and device identifiers documented", "patient_position": "Positioned according to target nerve and device workflow"},
    {"form_id": "sprint_or_pns_followup_programming", "title": "Peripheral nerve stimulator programming / follow-up", "condition_ids": ["peripheral_neuropathic_pain", "chronic_post_surgical_pain", "cluneal_neuralgia", "knee_osteoarthritis", "shoulder_oa_capsulitis"], "conditions": ["Peripheral nerve stimulation follow-up", "Chronic regional pain"], "region": "General / multisite pain", "guidance": "N/A - device programming/follow-up", "intervention_type": "Stimulation / neuromodulation", "procedure_group": "Peripheral nerve stimulation / PRF", "target": "Active PNS target/lead location documented from prior procedure", "approach": "Programming, impedance/status check, patient feedback, and setting adjustment", "needle": "N/A - implanted or percutaneous stimulator follow-up", "injectate_product": "Peripheral nerve stimulator programming; no injectate unless separately documented", "dose_volume": "Program settings, amplitude/frequency/pulse width if available, and patient response documented", "patient_position": "Comfortable position for programming and assessment"},
    {"form_id": "scs_trial_followup_template", "title": "Spinal cord stimulator trial / follow-up documentation", "condition_ids": ["lumbar_radiculopathy", "peripheral_neuropathic_pain", "crps", "chronic_post_surgical_pain"], "conditions": ["Failed back surgery syndrome", "CRPS", "Chronic neuropathic pain"], "region": "General / multisite pain", "guidance": "Fluoroscopy-guided for lead placement; N/A for programming/follow-up", "intervention_type": "Stimulation / neuromodulation", "procedure_group": "Spinal cord stimulation (SCS)", "target": "Epidural lead target level or active stimulation coverage region", "approach": "SCS trial/lead/programming workflow according to device protocol", "needle": "SCS needle/lead system or programmer as applicable", "injectate_product": "Spinal cord stimulation device workflow; local anesthetic/sedation as separately documented", "dose_volume": "Lead level, program settings, coverage, paresthesia-free program if used, and response documented", "patient_position": "Prone for lead placement; comfortable position for programming/follow-up"},
    {"form_id": "dorsal_root_ganglion_stimulation_template", "title": "Dorsal root ganglion stimulation trial / follow-up documentation", "condition_ids": ["crps", "peripheral_neuropathic_pain", "chronic_post_surgical_pain"], "conditions": ["CRPS", "Focal neuropathic pain"], "region": "General / multisite pain", "guidance": "Fluoroscopy-guided for lead placement; N/A for programming/follow-up", "intervention_type": "Stimulation / neuromodulation", "procedure_group": "Dorsal root ganglion stimulation (DRG-S)", "target": "Selected DRG target level(s) or active stimulation coverage region", "approach": "DRG stimulation trial/lead/programming workflow according to device protocol", "needle": "DRG stimulation lead system or programmer as applicable", "injectate_product": "DRG stimulation device workflow; local anesthetic/sedation as separately documented", "dose_volume": "Lead level, program settings, coverage, and response documented", "patient_position": "Prone for lead placement; comfortable position for programming/follow-up"},
    {"form_id": "basivertebral_nerve_ablation_intracept_template", "title": "Basivertebral nerve ablation / Intracept procedure documentation", "condition_ids": ["lumbar_facet_pain", "chronic_post_surgical_pain"], "conditions": ["Vertebrogenic low back pain", "Modic change-associated low back pain"], "region": "Lumbar spine", "guidance": "Fluoroscopy-guided according to device/procedure protocol", "intervention_type": "Ablation / PRF", "procedure_group": "Basivertebral nerve ablation (Intracept)", "target": "Basivertebral nerve target in selected vertebral body level(s)", "approach": "Transpedicular access according to device protocol", "needle": "Basivertebral nerve ablation access cannula/device system", "injectate_product": "Basivertebral nerve ablation device workflow; medications documented separately", "dose_volume": "Device, level(s), ablation settings, duration, and identifiers documented", "patient_position": "Prone"},
]


def _all_procedure_specs() -> list[dict[str, Any]]:
    return [*MISSING_PROCEDURE_SPECS, *ADVANCED_PAIN_PROCEDURE_SPECS]


ADDITIONAL_CONDITION_SPECS: list[dict[str, Any]] = [
    {"condition_id": "headache_cranial_neuralgia", "condition": "Headache / cranial neuralgia", "procedure_ids": ["occipital_nerve_block", "cervical_third_occipital_nerve_block_us", "occipital_nerve_prf_us", "supratrochlear_supraorbital_block_us", "auriculotemporal_block_us", "trigeminal_branch_block_us"]},
    {"condition_id": "trigeminal_neuralgia_facial_pain", "condition": "Trigeminal neuralgia / facial neuropathic pain", "procedure_ids": ["trigeminal_branch_block_us", "auriculotemporal_block_us", "ketamine_infusion_chronic_pain"]},
    {"condition_id": "post_mastectomy_chest_wall_pain", "condition": "Post-mastectomy / post-thoracotomy chest wall pain", "procedure_ids": ["intercostal_nerve_block_us", "thoracic_paravertebral_block_us", "serratus_anterior_plane_block_us", "pecs_block_us", "rhomboid_intercostal_plane_block_us", "peripheral_nerve_stimulation_trial_us"]},
    {"condition_id": "meralgia_paresthetica", "condition": "Meralgia paresthetica / lateral femoral cutaneous neuralgia", "procedure_ids": ["lateral_femoral_cutaneous_block_us", "peripheral_nerve_prf_us", "peripheral_nerve_stimulation_trial_us"]},
    {"condition_id": "tarsal_tunnel_tibial_neuralgia", "condition": "Tarsal tunnel syndrome / tibial neuralgia", "procedure_ids": ["tibial_nerve_block_us", "peripheral_nerve_prf_us", "peripheral_nerve_stimulation_trial_us"]},
    {"condition_id": "peroneal_neuralgia", "condition": "Common peroneal neuralgia / lateral leg neuropathic pain", "procedure_ids": ["peroneal_nerve_block_us", "peripheral_nerve_prf_us", "peripheral_nerve_stimulation_trial_us"]},
    {"condition_id": "saphenous_neuralgia", "condition": "Saphenous neuralgia / medial knee neuropathic pain", "procedure_ids": ["saphenous_adductor_canal_block_us", "peripheral_nerve_prf_us", "peripheral_nerve_stimulation_trial_us"]},
    {"condition_id": "obturator_neuralgia", "condition": "Obturator neuralgia / medial groin pain", "procedure_ids": ["obturator_nerve_block_us", "peripheral_nerve_prf_us"]},
    {"condition_id": "femoral_neuralgia", "condition": "Femoral neuralgia / anterior thigh neuropathic pain", "procedure_ids": ["femoral_nerve_block_us", "peripheral_nerve_prf_us"]},
    {"condition_id": "vertebrogenic_low_back_pain", "condition": "Vertebrogenic low back pain / Modic change-associated pain", "procedure_ids": ["basivertebral_nerve_ablation_intracept_template", "trigger_point_injections"]},
    {"condition_id": "failed_back_surgery_syndrome", "condition": "Failed back surgery syndrome / persistent spinal pain syndrome", "procedure_ids": ["caudal_esi_us", "caudal_esi_fluoro", "lumbar_paravertebral_block_us", "tlip_block_us", "scs_trial_followup_template", "dorsal_root_ganglion_stimulation_template", "ketamine_infusion_chronic_pain"]},
    {"condition_id": "phantom_limb_stump_pain", "condition": "Phantom limb pain / stump pain", "procedure_ids": ["peripheral_nerve_prf_us", "peripheral_nerve_stimulation_trial_us", "ketamine_infusion_chronic_pain"]},
    {"condition_id": "post_herniorrhaphy_groin_pain", "condition": "Post-herniorrhaphy groin pain", "procedure_ids": ["ilioinguinal_iliohypogastric_block_us", "genitofemoral_block_us", "peripheral_nerve_prf_us", "peripheral_nerve_stimulation_trial_us"]},
    {"condition_id": "abdominal_wall_pain", "condition": "Abdominal wall pain / ACNES / post-surgical abdominal wall pain", "procedure_ids": ["transversus_abdominis_plane_block_us", "ilioinguinal_iliohypogastric_block_us", "genitofemoral_block_us", "peripheral_nerve_prf_us", "peripheral_nerve_stimulation_trial_us"]},
    {"condition_id": "sympathetically_maintained_pain", "condition": "Sympathetically maintained pain", "procedure_ids": ["stellate_ganglion_block_us", "lumbar_sympathetic_block_us", "peripheral_nerve_prf_us", "ketamine_infusion_chronic_pain"]},
    {"condition_id": "flank_pain_regional_pain", "condition": "Flank pain / thoracolumbar regional pain", "procedure_ids": ["quadratus_lumborum_block_us", "erector_spinae_plane_block_us", "tlip_block_us", "trigger_point_injections"]},
    {"condition_id": "pelvic_visceral_pain", "condition": "Chronic pelvic / visceral pelvic pain", "procedure_ids": ["pudendal_nerve_block_us", "ganglion_impar_us", "coccyx_ganglion_impar_block_fluoro", "superior_hypogastric_plexus_block_us", "ketamine_infusion_chronic_pain"]},
]


def add_recommended_next_procedure_section(data: dict[str, Any]) -> None:
    for form in data.get("forms", []):
        if form.get("form_type") != "Procedure":
            continue
        _add_next_procedure_defaults(form)
        _add_next_procedure_fields(form)
        _add_next_procedure_template(form)


def _add_next_procedure_defaults(form: dict[str, Any]) -> None:
    defaults = form.setdefault("defaults", form.get("procedure_defaults", {}))
    text = " ".join(
        str(form.get(key, "")) for key in ("title", "family", "category", "form_id")
    ).lower()
    defaults.setdefault("next_procedure_medication_choice", _first_default(defaults, [
        "injectate_product",
        "ha_product",
        "ketamine_product",
        "post_lesion_injectate",
        "prolo_solution",
        "hydrodissection_solution",
    ]))
    defaults.setdefault("next_procedure_dose", _dose_default(defaults))
    defaults.setdefault("next_procedure_technique", _technique_default(defaults))
    defaults.setdefault("next_procedure_patient_position", defaults.get("patient_position", "Same as current procedure unless changed."))
    defaults.setdefault("next_procedure_premedication", "Same as current procedure if used; otherwise none planned unless clinically indicated.")
    defaults.setdefault(
        "next_procedure_pre_procedure_comments",
        _pre_procedure_default(text),
    )
    defaults.setdefault(
        "next_procedure_intra_procedure_comments",
        "Use the same documented technique unless anatomy, response, or safety considerations require modification.",
    )
    defaults.setdefault(
        "next_procedure_post_procedure_comments",
        "Reassess response, adverse effects, function, and need for further treatment after the next procedure.",
    )


def _add_next_procedure_fields(form: dict[str, Any]) -> None:
    fields = form.setdefault("fields", [])
    existing = {field.get("key") for field in fields}
    for field in NEXT_PROCEDURE_FIELDS:
        if field["key"] not in existing:
            fields.append(dict(field))


def _add_next_procedure_template(form: dict[str, Any]) -> None:
    for key in ("narrative_template", "template"):
        template = form.get(key)
        if isinstance(template, str) and "Recommended next procedure:" not in template:
            form[key] = template + NEXT_PROCEDURE_TEMPLATE


def add_comprehensive_procedure_taxonomy(data: dict[str, Any]) -> None:
    """Add navigation metadata and missing office-based procedure forms.

    The source workbook remains the clinical backbone. This augmentation adds a
    practical procedure-selection taxonomy across all existing forms and fills
    obvious office-based ultrasound/landmark gaps without deleting fluoroscopy
    forms already generated in earlier builds.
    """

    add_chronic_pain_condition_shells(data)
    forms = data.setdefault("forms", [])
    forms_by_id = {form.get("form_id"): form for form in forms}
    existing_ids = set(forms_by_id)
    for spec in _all_procedure_specs():
        form = forms_by_id.get(spec["form_id"])
        if form is None:
            form = _form_from_missing_spec(spec)
            forms.append(form)
            forms_by_id[spec["form_id"]] = form
            existing_ids.add(spec["form_id"])
        else:
            _apply_spec_metadata(form, spec)

    forms_by_id = {form.get("form_id"): form for form in forms}
    for condition in data.get("conditions", []):
        condition_id = condition.get("condition_id")
        _annotate_condition(condition)
        procedure_ids = condition.setdefault("procedure_ids", [])
        for spec in _all_procedure_specs():
            if condition_id in spec.get("condition_ids", []) and spec["form_id"] not in procedure_ids:
                procedure_ids.append(spec["form_id"])
        condition["procedure_ids"] = [pid for pid in procedure_ids if pid in forms_by_id]

    condition_lookup = {
        condition.get("condition_id"): condition
        for condition in data.get("conditions", [])
    }
    form_to_conditions: dict[str, list[dict[str, Any]]] = {}
    for condition in data.get("conditions", []):
        for form_id in condition.get("procedure_ids", []):
            form_to_conditions.setdefault(form_id, []).append(condition)
    for form in forms:
        if form.get("form_type") == "Procedure":
            _annotate_form_navigation(form, form_to_conditions.get(form.get("form_id"), []))
        elif form.get("form_type") in {"History", "Physical Exam"}:
            condition = next(
                (
                    c for c in condition_lookup.values()
                    if c.get("history_form_id") == form.get("form_id")
                    or c.get("exam_form_id") == form.get("form_id")
                ),
                None,
            )
            if condition:
                form["navigator"] = {
                    "region": condition.get("navigator", {}).get("region", "General"),
                    "condition": condition.get("condition", ""),
                    "guidance_options": ["N/A"],
                    "intervention_type": form.get("form_type", ""),
                    "procedure_group": form.get("form_type", ""),
                }


def add_chronic_pain_condition_shells(data: dict[str, Any]) -> None:
    conditions = data.setdefault("conditions", [])
    forms = data.setdefault("forms", [])
    existing_conditions = {condition.get("condition_id") for condition in conditions}
    existing_forms = {form.get("form_id") for form in forms}
    for spec in ADDITIONAL_CONDITION_SPECS:
        if spec["condition_id"] in existing_conditions:
            continue
        history_id = f"hist_{spec['condition_id']}"
        exam_id = f"exam_{spec['condition_id']}"
        if history_id not in existing_forms:
            forms.append(_condition_form(spec, history_id, "History"))
            existing_forms.add(history_id)
        if exam_id not in existing_forms:
            forms.append(_condition_form(spec, exam_id, "Physical Exam"))
            existing_forms.add(exam_id)
        conditions.append(
            {
                "condition_id": spec["condition_id"],
                "condition": spec["condition"],
                "history_form_id": history_id,
                "exam_form_id": exam_id,
                "procedure_ids": list(spec.get("procedure_ids", [])),
            }
        )
        existing_conditions.add(spec["condition_id"])


def _condition_form(spec: dict[str, Any], form_id: str, form_type: str) -> dict[str, Any]:
    title = f"{form_type} - {spec['condition']}"
    prefix = "Hx" if form_type == "History" else "PE"
    if form_type == "History":
        fields = [
            {"section": "History", "key": "condition_focus", "label": "Condition focus", "default_layer": "No Default", "input_type": "textarea", "required": True, "options": "", "help": "Focused condition-specific history."},
            {"section": "History", "key": "presenting_complaint", "label": "Presenting complaint / pain problem", "default_layer": "No Default", "input_type": "textarea", "required": True, "options": "", "help": "Current pain complaint and chronology."},
            {"section": "History", "key": "pain_location_distribution", "label": "Pain location / distribution", "default_layer": "No Default", "input_type": "textarea", "required": True, "options": "", "help": "Map region, radiation, neuropathic distribution, and focal tenderness."},
            {"section": "History", "key": "functional_limitations", "label": "Function / goals", "default_layer": "No Default", "input_type": "textarea", "required": True, "options": "", "help": "Functional impact and patient goals."},
            {"section": "History", "key": "prior_treatments", "label": "Prior treatments / response", "default_layer": "No Default", "input_type": "textarea", "required": True, "options": "", "help": "Medication, therapy, injections, surgery, and response."},
            {"section": "History", "key": "current_medications", "label": "Current medications / anticoagulants", "default_layer": "No Default", "input_type": "textarea", "required": True, "options": "", "help": "Include relevant anticoagulants, antiplatelets, allergy considerations."},
            {"section": "History", "key": "red_flags_neuro_screen", "label": "Red flags / neurologic screen", "default_layer": "No Default", "input_type": "textarea", "required": True, "options": "", "help": "Safety screen relevant to procedure planning."},
            {"section": "History", "key": "imaging_labs_tests", "label": "Imaging / tests reviewed", "default_layer": "No Default", "input_type": "textarea", "required": False, "options": "", "help": "Imaging, EMG/NCS, labs, or other investigations."},
            {"section": "Plan", "key": "history_impression_plan", "label": "History impression / plan", "default_layer": "No Default", "input_type": "textarea", "required": True, "options": "", "help": "Working diagnosis and plan."},
        ]
        template = (
            f"{title}\n\n"
            "Condition focus: {{condition_focus}}\n"
            "Presenting complaint: {{presenting_complaint}}\n"
            "Pain distribution: {{pain_location_distribution}}\n"
            "Function/goals: {{functional_limitations}}\n"
            "Prior treatments: {{prior_treatments}}\n"
            "Medications/safety: {{current_medications}}\n"
            "Red flags/neuro screen: {{red_flags_neuro_screen}}\n"
            "Imaging/tests: {{imaging_labs_tests}}\n"
            "Impression/plan: {{history_impression_plan}}"
        )
    else:
        fields = [
            {"section": "Exam", "key": "condition_focus", "label": "Condition focus", "default_layer": "No Default", "input_type": "textarea", "required": True, "options": "", "help": "Focused exam context."},
            {"section": "Exam", "key": "inspection_function", "label": "Inspection / function", "default_layer": "No Default", "input_type": "textarea", "required": True, "options": "", "help": "Inspection, gait/use, posture, functional provocation."},
            {"section": "Exam", "key": "palpation_findings", "label": "Palpation / tenderness", "default_layer": "No Default", "input_type": "textarea", "required": True, "options": "", "help": "Tenderness, trigger points, enthesis, joint line, nerve course."},
            {"section": "Exam", "key": "range_strength_neuro", "label": "Range / strength / neurologic findings", "default_layer": "No Default", "input_type": "textarea", "required": True, "options": "", "help": "ROM, strength, sensory/reflex or regional neurologic findings."},
            {"section": "Exam", "key": "condition_specific_exam", "label": "Condition-specific provocative tests", "default_layer": "No Default", "input_type": "textarea", "required": True, "options": "", "help": "Special tests relevant to target selection."},
            {"section": "Exam", "key": "red_flag_exam_findings", "label": "Red flag / safety findings", "default_layer": "No Default", "input_type": "textarea", "required": True, "options": "", "help": "Findings that alter procedure risk or urgency."},
            {"section": "Assessment", "key": "pain_generator_impression", "label": "Pain generator impression", "default_layer": "No Default", "input_type": "textarea", "required": True, "options": "", "help": "Most likely pain generator(s)."},
            {"section": "Assessment", "key": "procedural_target_assessment", "label": "Procedural target assessment", "default_layer": "No Default", "input_type": "textarea", "required": True, "options": "", "help": "Proposed target(s), guidance needs, and anatomy considerations."},
            {"section": "Plan", "key": "exam_plan", "label": "Exam-based plan", "default_layer": "No Default", "input_type": "textarea", "required": True, "options": "", "help": "Plan after exam."},
        ]
        template = (
            f"{title}\n\n"
            "Condition focus: {{condition_focus}}\n"
            "Inspection/function: {{inspection_function}}\n"
            "Palpation: {{palpation_findings}}\n"
            "ROM/strength/neuro: {{range_strength_neuro}}\n"
            "Condition-specific exam: {{condition_specific_exam}}\n"
            "Red flag findings: {{red_flag_exam_findings}}\n"
            "Pain generator impression: {{pain_generator_impression}}\n"
            "Procedural target assessment: {{procedural_target_assessment}}\n"
            "Plan: {{exam_plan}}"
        )
    return {
        "form_id": form_id,
        "form_type": form_type,
        "title": title,
        "family": form_type,
        "category": form_type,
        "condition_tags": spec["condition"],
        "template_sheet": _sheet_name(f"{prefix}_{spec['condition_id']}"),
        "status": "v0.8 generated chronic-pain condition shell - physician review required",
        "fields": fields,
        "narrative_template": template,
    }


def _form_from_missing_spec(spec: dict[str, Any]) -> dict[str, Any]:
    defaults = {
        "patient_position": spec.get("patient_position", "Positioned to expose and relax the target region"),
        "guidance": spec["guidance"],
        "guidance_phrase": _guidance_phrase(spec["guidance"]),
        "transducer_or_equipment": spec.get("transducer_or_equipment") or _equipment_for_guidance(spec["guidance"]),
        "approach": spec["approach"],
        "target": spec["target"],
        "needle": spec["needle"],
        "injectate_product": spec["injectate_product"],
        "dose_volume": spec["dose_volume"],
        "diluent_anesthetic": spec.get("diluent_anesthetic", _mix_default(spec)),
    }
    return {
        "form_id": spec["form_id"],
        "form_type": "Procedure",
        "title": spec["title"],
        "family": spec["procedure_group"],
        "category": spec["procedure_group"],
        "condition_tags": "; ".join(spec.get("conditions", [])),
        "conditions": spec.get("conditions", []),
        "template_sheet": _sheet_name(spec["form_id"]),
        "status": "v0.8 generated taxonomy expansion - physician review required",
        "defaults": defaults,
        "fields": [dict(field) for field in COMMON_PROCEDURE_FIELDS],
        "narrative_template": COMMON_PROCEDURE_TEMPLATE.format(title=spec["title"]),
        "navigator": {
            "region": spec["region"],
            "guidance_options": _guidance_options(spec["guidance"]),
            "intervention_type": spec["intervention_type"],
            "procedure_group": spec["procedure_group"],
        },
    }


def _apply_spec_metadata(form: dict[str, Any], spec: dict[str, Any]) -> None:
    form["family"] = spec.get("procedure_group", form.get("family", "Procedure"))
    form["category"] = spec.get("procedure_group", form.get("category", "Procedure"))
    form["condition_tags"] = "; ".join(spec.get("conditions", [])) or form.get("condition_tags", "")
    defaults = form.setdefault("defaults", {})
    procedure_defaults = form.setdefault("procedure_defaults", {})
    for key, value in {
        "patient_position": spec.get("patient_position"),
        "guidance": spec.get("guidance"),
        "guidance_phrase": _guidance_phrase(spec.get("guidance", "")),
        "transducer_or_equipment": spec.get("transducer_or_equipment") or _equipment_for_guidance(spec.get("guidance", "")),
        "approach": spec.get("approach"),
        "target": spec.get("target"),
        "needle": spec.get("needle"),
        "injectate_product": spec.get("injectate_product"),
        "dose_volume": spec.get("dose_volume"),
        "diluent_anesthetic": spec.get("diluent_anesthetic", _mix_default(spec)),
    }.items():
        if value:
            defaults.setdefault(key, value)
            procedure_defaults.setdefault(key, value)
    form["navigator"] = {
        "region": spec["region"],
        "guidance_options": _guidance_options(spec["guidance"]),
        "intervention_type": spec["intervention_type"],
        "procedure_group": spec["procedure_group"],
    }


def _annotate_condition(condition: dict[str, Any]) -> None:
    name = str(condition.get("condition", ""))
    condition["navigator"] = {
        "region": _region_from_text(name),
        "condition": name,
        "pain_generator": _pain_generator_from_text(name),
    }


def _annotate_form_navigation(form: dict[str, Any], conditions: list[dict[str, Any]]) -> None:
    defaults = form.get("defaults") or form.get("procedure_defaults") or {}
    guidance_text = str(defaults.get("guidance") or defaults.get("imaging_modality") or form.get("title", ""))
    title_text = " ".join(str(form.get(key, "")) for key in ("title", "family", "category", "condition_tags"))
    navigator = form.setdefault("navigator", {})
    navigator.setdefault("region", _form_region(form, conditions))
    navigator.setdefault("condition", "; ".join(c.get("condition", "") for c in conditions) or form.get("condition_tags", ""))
    navigator.setdefault("guidance_options", _guidance_options(guidance_text))
    navigator.setdefault("intervention_type", _intervention_type_from_text(title_text))
    navigator.setdefault("procedure_group", _procedure_group_from_text(title_text))


def _form_region(form: dict[str, Any], conditions: list[dict[str, Any]]) -> str:
    if conditions:
        return conditions[0].get("navigator", {}).get("region", "General")
    return _region_from_text(" ".join(str(form.get(key, "")) for key in ("title", "condition_tags", "family")))


def _region_from_text(text: str) -> str:
    lower = text.lower()
    mappings = [
        ("Cervical spine / head", ["cervical", "occipital", "cervicogenic", "headache", "stellate"]),
        ("Thoracic spine / chest wall", ["thoracic", "intercostal", "rib", "chest wall"]),
        ("Lumbar spine", ["lumbar", "sciatica", "radicular", "facet", "low back"]),
        ("Pelvis / sacroiliac / hip", ["sacroiliac", "coccy", "pudendal", "pelvic", "piriformis", "gluteal", "hip", "trochanter", "cluneal"]),
        ("Shoulder", ["shoulder", "rotator", "subacromial", "biceps", "glenohumeral", "acromioclavicular"]),
        ("Elbow", ["elbow", "epicondyl"]),
        ("Wrist / hand", ["carpal", "thumb", "finger", "de quervain", "wrist", "cmc"]),
        ("Knee", ["knee", "genicular", "patellar", "saphenous"]),
        ("Foot / ankle", ["ankle", "achilles", "plantar", "morton", "forefoot", "heel", "tarsal", "tibial"]),
        ("Central sensitization / infusion", ["fibromyalgia", "central sensitization", "ketamine", "crps"]),
    ]
    for region, needles in mappings:
        if any(needle in lower for needle in needles):
            return region
    return "General / multisite pain"


def _pain_generator_from_text(text: str) -> str:
    lower = text.lower()
    if any(term in lower for term in ["radicular", "neuralgia", "neuropathic", "nerve"]):
        return "Neuropathic / nerve"
    if any(term in lower for term in ["facet", "joint", "osteoarthritis", "cmc", "ankle", "hip", "knee"]):
        return "Joint / facet"
    if any(term in lower for term in ["tendon", "fascia", "epicondyl", "achilles", "plantar", "biceps"]):
        return "Tendon / enthesis"
    if any(term in lower for term in ["myofascial", "trigger", "fibromyalgia"]):
        return "Myofascial / central sensitization"
    return "Mixed / regional pain"


def _guidance_options(text: str) -> list[str]:
    lower = text.lower()
    options: list[str] = []
    if "ultrasound" in lower or "sonograph" in lower:
        options.append("Ultrasound-guided")
    if "fluoro" in lower:
        options.append("Fluoroscopy-guided")
    if "landmark" in lower or "palpation" in lower:
        options.append("Landmark-guided")
    if "n/a" in lower or "infusion" in lower:
        options.append("N/A")
    return options or ["Image-guided / other"]


def _intervention_type_from_text(text: str) -> str:
    lower = text.lower()
    if any(term in lower for term in ["rfa", "radiofrequency", "ablation", "pulsed"]):
        return "Ablation / PRF"
    if any(term in lower for term in ["prp", "prolo", "hyaluronic", "ha", "fenestration"]):
        return "Regenerative / viscosupplementation"
    if "infusion" in lower:
        return "Infusion"
    if any(term in lower for term in ["block", "hydrodissection"]):
        return "Block / hydrodissection"
    return "Injection"


def _procedure_group_from_text(text: str) -> str:
    lower = text.lower()
    groups = [
        ("Epidural steroid injections (ESI)", ["epidural", "esi", "transforaminal", "caudal"]),
        ("Facet / medial branch procedures", ["facet", "medial branch", "mbb"]),
        ("Peripheral nerve blocks", ["nerve block", "perineural", "hydrodissection", "neuralgia"]),
        ("Joint injections", ["joint", "intra-articular", "glenohumeral", "tibiotalar", "cmc"]),
        ("Tendon / enthesis procedures", ["tendon", "fascia", "epicondyl", "achilles", "plantar", "biceps"]),
        ("Regional anesthesia / fascial plane blocks", ["plane block", "quadratus", "erector", "tlip", "paravertebral"]),
        ("Trigger point / myofascial", ["trigger point", "myofascial"]),
        ("Infusion therapy", ["infusion", "ketamine"]),
        ("Ablation / neuromodulation", ["ablation", "radiofrequency", "rfa", "stimulation", "intracept"]),
    ]
    for group, needles in groups:
        if any(needle in lower for needle in needles):
            return group
    return "Office-based pain procedure"


def _guidance_phrase(guidance: str) -> str:
    lower = guidance.lower()
    if "ultrasound" in lower and "landmark" in lower:
        return "Ultrasound guidance and/or landmark guidance was used according to the selected target, depth, and safety considerations. Relevant anatomy and needle path were documented as feasible."
    if "ultrasound" in lower:
        return "Real-time ultrasound guidance was used. Needle tip location, target region, injectate spread, and relevant surrounding structures were visualized as feasible."
    if "fluoro" in lower:
        return "Fluoroscopic image guidance was used with standard radiation safety precautions and contrast confirmation when applicable and not contraindicated."
    if "landmark" in lower or "palpation" in lower:
        return "Anatomic landmarks and palpation-guided target confirmation were used. No image guidance was used unless otherwise documented."
    return "Guidance and target confirmation were performed according to the selected technique and documented findings."


def _equipment_for_guidance(guidance: str) -> str:
    lower = guidance.lower()
    if "ultrasound" in lower:
        return "Ultrasound transducer selected according to target depth and body habitus"
    if "fluoro" in lower:
        return "Fluoroscopy unit"
    if "landmark" in lower or "palpation" in lower:
        return "Landmark palpation / office procedure setup"
    return "Procedure-specific equipment"


def _mix_default(spec: dict[str, Any]) -> str:
    text = " ".join(str(spec.get(key, "")) for key in ("title", "intervention_type", "injectate_product")).lower()
    if "prp" in text:
        return "Autologous PRP only unless physician documents adjunct."
    if "hyaluronic" in text:
        return "Product-specific hyaluronic acid preparation; no additional mix unless documented."
    if "prolo" in text or "dextrose" in text:
        return "Dextrose/local anesthetic solution per clinic protocol; concentration documented."
    if "steroid" in text:
        return "Local anesthetic and/or preservative-free saline as selected."
    return "Medication mix selected by physician and documented."


def _sheet_name(form_id: str) -> str:
    cleaned = "".join(ch for ch in form_id if ch.isalnum() or ch == "_")
    return cleaned[:31]


def _first_default(defaults: dict[str, Any], keys: list[str]) -> str:
    for key in keys:
        value = defaults.get(key)
        if value:
            return str(value)
    return "Same medication/product choice as current procedure unless changed."


def _dose_default(defaults: dict[str, Any]) -> str:
    parts = [
        defaults.get("dose_volume"),
        defaults.get("total_volume"),
        defaults.get("lesion_settings"),
        defaults.get("infusion_rate"),
    ]
    value = "; ".join(str(part) for part in parts if part)
    return value or "Same dose/volume/settings as current procedure unless changed."


def _technique_default(defaults: dict[str, Any]) -> str:
    parts = [
        defaults.get("guidance") or defaults.get("imaging_modality"),
        defaults.get("approach"),
        defaults.get("target") or defaults.get("levels_targets"),
        defaults.get("needle") or defaults.get("cannula"),
    ]
    value = "; ".join(str(part) for part in parts if part)
    return value or "Same technique as current procedure unless changed."


def _pre_procedure_default(form_text: str) -> str:
    if "rfa" in form_text or "radiofrequency" in form_text or "ablation" in form_text:
        return "If repeating nerve ablation/RFA, usual interval is about every year or longer unless physician documents a different rationale; reassess indication, diagnostic response, neurologic status, and contraindications before proceeding."
    if "steroid" in form_text or "corticosteroid" in form_text:
        return "If repeating steroid, usual interval is every 3 months or longer unless physician documents a different rationale; reassess indication and contraindications before proceeding."
    return "Reassess indication, response to the current procedure, contraindications, patient preference, and affordability before proceeding."


QUICK_TEXT_OPTIONS: dict[str, list[str]] = {
    "allergy_infection_anticoagulant_screen": [
        "No known relevant allergies; no active infection symptoms; anticoagulant/antiplatelet status reviewed.",
        "Medication/allergy list reviewed; no contraindication identified today.",
        "Anticoagulant/antiplatelet plan reviewed and documented before proceeding.",
        "No fever, systemic infection symptoms, local skin infection, or open wound at the planned needle entry site reported today.",
        "Diabetes/immunosuppression status reviewed; steroid risk and post-procedure monitoring discussed where applicable.",
        "Pregnancy status, allergy history, anticoagulant plan, and medication list reviewed according to clinic protocol.",
        "Patient denies contrast, latex, chlorhexidine/iodine, local anesthetic, or steroid allergy relevant to today's plan.",
        "Recent antibiotics, vaccination timing, infection symptoms, and wound concerns reviewed before proceeding.",
        "No interval change in medical status that alters the planned procedure was identified today.",
        "Patient-specific safety concern documented below and plan modified accordingly.",
    ],
    "clinical_indication": [
        "Persistent function-limiting pain despite conservative management; procedure offered for diagnostic and/or therapeutic benefit.",
        "Symptoms, examination, and available imaging are concordant with the planned target.",
        "Prior treatment response and patient goals reviewed; patient wishes to proceed.",
        "Procedure selected to clarify the pain generator and guide further treatment planning.",
        "Pain distribution and provocative examination findings are consistent with the selected nerve/joint/tendon/enthesis target.",
        "Repeat procedure considered because prior response was clinically meaningful and duration of benefit supports repeat treatment.",
        "Regenerative/viscosupplementation option selected after discussion of expected onset, cost, alternatives, and uncertainty of response.",
        "Ablation/PRF considered after diagnostic response and persistent recurrent pain in the same target distribution.",
        "Neuromodulation/stimulation option considered for refractory neuropathic pain after conservative and injection-based options were reviewed.",
        "Patient preference, functional goals, affordability, and medication risk profile were reviewed before final procedure selection.",
    ],
    "image_saved": [
        "Representative images saved to clinic imaging archive.",
        "Image storage not technically feasible; guidance findings documented in note.",
        "Fluoroscopic images stored according to clinic workflow.",
        "Pre-injection target image and post-injection spread image saved.",
        "Needle tip/cannula position image saved before treatment delivery.",
        "Ultrasound image demonstrating target anatomy, adjacent vessels, and final needle tip position saved.",
        "No image saved because procedure was landmark-based; anatomic landmarks and endpoint are documented.",
        "Device/programming procedure only; image archive not applicable.",
    ],
    "needle_visualization": [
        "Needle advanced under continuous in-plane visualization with tip position confirmed before injection.",
        "Needle/cannula position confirmed with image guidance before treatment.",
        "Needle path adjusted to avoid visible vessels and surrounding sensitive structures.",
        "Needle advanced incrementally with frequent tip confirmation before each injection.",
        "Out-of-plane approach used; needle tip location confirmed by tissue movement, hydrodissection, and/or target response.",
        "RF cannula position confirmed at the intended target before sensory/motor testing and treatment.",
        "Lead/introducer position confirmed according to device protocol before stimulation testing/programming.",
        "Landmark endpoint reached without paresthesia, vascular puncture, or concerning resistance.",
        "Needle repositioned until injectate spread/target endpoint was acceptable.",
    ],
    "aspiration_result": [
        "Negative",
        "No blood or fluid aspirated before injection.",
        "Not applicable.",
        "Negative aspiration before each aliquot.",
        "Negative aspiration and no paresthesia before injection.",
        "Sensory/motor testing was acceptable before RF treatment.",
        "Stimulation response/coverage was acceptable before lead finalization.",
        "Aspiration was not applicable because no injectate was delivered.",
    ],
    "injection_character": [
        "Injectate spread was visualized in the intended tissue plane/target region without high resistance.",
        "Injection proceeded smoothly without paresthesia, severe pain, or concerning resistance.",
        "Injectate distribution was acceptable for the planned target.",
        "Hydrodissection opened the intended plane and confirmed extraneural/peritendinous spread.",
        "Perineural spread was seen without nerve swelling or intraneural injection appearance.",
        "Intra-articular or pericapsular spread was acceptable for the intended target.",
        "Fascial plane spread tracked along the expected anatomic plane.",
        "No vascular uptake, unexpected pain, or concerning resistance occurred during injection.",
        "Treatment endpoint was achieved; no injectate was required beyond local anesthetic as documented.",
    ],
    "immediate_response": [
        "Tolerated well; immediate response to be assessed over the expected therapeutic window.",
        "No immediate complication; post-procedure pain/function response reviewed before discharge.",
        "Immediate pain score and functional response documented after reassessment.",
        "Patient remained neurologically at baseline after the procedure.",
        "Expected temporary sensory/motor change reviewed before discharge.",
        "Initial diagnostic response was reviewed, recognizing that anesthetic onset and steroid/regenerative effect differ.",
        "Patient ambulated/transitioned from procedure position without new concerning symptoms.",
        "Device stimulation/programming response was reviewed with the patient before discharge.",
        "No vasovagal symptoms, allergic symptoms, or new neurologic deficit observed during immediate recovery.",
    ],
    "complications": [
        "None.",
        "No immediate adverse event observed.",
        "Transient expected procedural discomfort only.",
        "Transient vasovagal symptoms occurred and resolved with supportive care.",
        "Minor superficial bleeding/oozing controlled with local pressure.",
        "Transient paresthesia occurred during needle placement and resolved after repositioning.",
        "Procedure modified or stopped because of patient discomfort/safety concern, as documented.",
        "No allergic reaction, infection concern, new neurologic deficit, or hematoma observed immediately.",
    ],
    "follow_up_plan": [
        "Follow-up arranged according to response and treatment plan; patient advised to track pain, function, and adverse effects.",
        "Reassess pain score, functional change, medication use, and adverse effects at follow-up.",
        "Patient will contact clinic earlier for concerning symptoms or inadequate response.",
        "Pain diary requested to capture percent relief, duration of benefit, activity tolerance, and medication change.",
        "If diagnostic block is positive, consider confirmatory block and/or ablation according to clinic protocol.",
        "If steroid response is beneficial but temporary, repeat interval should respect safety limits and clinical necessity.",
        "If inadequate response, reassess diagnosis, target selection, imaging, and alternative procedure options.",
        "For regenerative or viscosupplementation treatment, reassess over the expected delayed response window.",
        "For stimulation/neuromodulation, review coverage, functional response, device tolerance, and programming needs.",
    ],
    "post_procedure_instructions": [
        "Post-procedure instructions and warning signs reviewed; patient advised to seek urgent care for concerning symptoms.",
        "Activity modification, expected soreness, medication precautions, and red flags reviewed.",
        "Written and verbal aftercare instructions provided according to clinic protocol.",
        "Avoid strenuous activity for the remainder of the day; resume usual activity gradually as tolerated unless otherwise instructed.",
        "Avoid soaking/submerging the injection site for 24 hours or according to clinic protocol.",
        "Monitor for fever, progressive redness/swelling, severe escalating pain, new weakness/numbness, bowel/bladder changes, or allergic symptoms.",
        "For steroid procedures, delayed onset, transient flare, and glucose effects were reviewed where applicable.",
        "For PRP/prolotherapy, post-procedure soreness and medication restrictions were reviewed according to clinic protocol.",
        "For ablation/PRF, expected neuritis/soreness timeline and delayed benefit window were reviewed.",
        "For stimulation/device procedures, dressing care, activity restrictions, device contact instructions, and red flags were reviewed.",
    ],
    "baseline_pain_function": [
        "Baseline pain score documented; pain limits walking, stairs, transfers, sleep, work, exercise, or self-care as described by patient.",
        "Baseline function and patient-specific goals reviewed before treatment.",
        "Pain diary baseline reviewed before procedure.",
        "Patient identifies the main functional goal as improved activity tolerance and reduced medication reliance.",
        "Baseline neurologic symptoms and functional limitations reviewed before intervention.",
    ],
    "levels_targets": [
        "Target level(s)/site(s) confirmed with patient, exam, and available imaging before procedure.",
        "Right-sided target(s) as documented.",
        "Left-sided target(s) as documented.",
        "Bilateral target(s) as documented.",
        "Most symptomatic level/site treated today; additional targets deferred unless clinically indicated.",
        "Multiple targets treated because symptoms and exam findings were concordant at each site.",
    ],
    "total_volume": [
        "Total volume delivered as documented in medication fields.",
        "Low-volume diagnostic injectate delivered by target.",
        "Total volume divided among documented targets.",
        "No therapeutic injectate delivered beyond local anesthetic for needle/cannula placement.",
        "Device/RF settings documented; total injectate volume not applicable except local anesthetic.",
    ],
    "lot_expiry": [
        "Lot/expiry recorded in clinic medication administration workflow.",
        "Product identifiers, lot, and expiry reviewed and documented where applicable.",
        "Autologous product prepared and documented according to clinic PRP workflow.",
        "Device identifiers and programming details documented according to device workflow.",
        "Not applicable for this encounter.",
    ],
    "next_procedure_pre_procedure_comments": [
        "Reassess indication, response to current procedure, contraindications, patient preference, and affordability before proceeding.",
        "Repeat only if clinically indicated after response and safety review.",
        "Confirm medication/product availability, consent, and interval safety before booking.",
        "For steroid repeat, confirm minimum interval and cumulative steroid exposure are clinically appropriate.",
        "For ablation repeat, confirm recurrence pattern and prior duration of benefit before repeating.",
        "For stimulation follow-up, confirm device status, wound status, coverage, charging/use pattern, and programming needs.",
        "If response is inadequate, reassess pain generator before repeating the same target.",
    ],
    "next_procedure_intra_procedure_comments": [
        "Use same technique unless anatomy, response, or safety considerations require modification.",
        "Adjust target/approach based on updated exam, imaging, and response to previous procedure.",
        "Document any change in guidance, target, needle/cannula, or device settings.",
        "Use ultrasound, fluoroscopy, landmark, or device workflow selected at the time of procedure.",
        "Consider lower volume, alternate plane, alternate target, or staged targets if prior spread/response was suboptimal.",
        "For RF/PRF, repeat sensory/motor testing and document settings rather than carrying forward prior settings blindly.",
        "For regenerative treatment, document product preparation/yield and target-specific fenestration or injection pattern.",
    ],
    "next_procedure_post_procedure_comments": [
        "Reassess response, adverse effects, function, and need for further treatment after the next procedure.",
        "Track pain diary, functional goals, and medication change after the next procedure.",
        "Review whether further repeat procedure remains appropriate before additional treatment.",
        "Review delayed onset window appropriate to steroid, HA, PRP, prolotherapy, ablation, or stimulation.",
        "Document percent relief, duration, functional gain, adverse effects, and patient preference before further repeat treatment.",
        "For device treatment, review coverage map, programming changes, wound/device concerns, and next programming interval.",
    ],
}

SECTION_QUICK_OPTIONS: dict[str, list[str]] = {
    "Safety": [
        "Reviewed today and no patient-specific contraindication identified.",
        "Patient-specific exception documented in the free-text field.",
    ],
    "Outcome": [
        "No immediate complication observed.",
        "Response will be reassessed after the expected onset window.",
    ],
    "Disposition": [
        "Aftercare, red flags, and follow-up plan reviewed with patient.",
    ],
}

PROCEDURE_CONTEXT_SOURCES: dict[str, list[str]] = {
    "diagnosis": [
        "condition_focus",
        "pain_generator_impression",
        "history_impression_plan",
    ],
    "clinical_indication": [
        "presenting_complaint",
        "pain_location_distribution",
        "functional_limitations",
        "prior_treatments",
        "imaging_labs_tests",
        "pain_generator_impression",
        "procedural_target_assessment",
    ],
    "allergy_infection_anticoagulant_screen": [
        "red_flags_neuro_screen",
        "red_flag_exam_findings",
        "current_medications",
    ],
    "image_saved": [
        "imaging_labs_tests",
        "procedural_target_assessment",
    ],
    "needle_visualization": [
        "procedural_target_assessment",
        "condition_specific_exam",
    ],
    "immediate_response": [
        "history_impression_plan",
        "exam_plan",
    ],
    "follow_up_plan": [
        "history_impression_plan",
        "exam_plan",
        "patient_preferences_affordability",
    ],
    "next_procedure_pre_procedure_comments": [
        "history_impression_plan",
        "exam_plan",
        "patient_preferences_affordability",
    ],
}


def add_fast_fill_assist(data: dict[str, Any]) -> None:
    for form in data.get("forms", []):
        for field in form.get("fields", []):
            _add_quick_options(field)
            _add_context_sources(form, field)


def _add_quick_options(field: dict[str, Any]) -> None:
    if field.get("input_type") not in {"text", "textarea"}:
        return

    options: list[str] = []
    key_options = QUICK_TEXT_OPTIONS.get(str(field.get("key", "")), [])
    section_options = SECTION_QUICK_OPTIONS.get(str(field.get("section", "")), [])
    options.extend(key_options)
    options.extend(section_options)
    if not options:
        return

    existing = field.get("quick_options", [])
    if isinstance(existing, str):
        existing = [item.strip() for item in existing.split(";") if item.strip()]
    merged = list(dict.fromkeys([*existing, *options]))
    field["quick_options"] = merged


def _add_context_sources(form: dict[str, Any], field: dict[str, Any]) -> None:
    if form.get("form_type") != "Procedure":
        return
    sources = PROCEDURE_CONTEXT_SOURCES.get(str(field.get("key", "")))
    if sources:
        field["context_sources"] = sources
