(*
   --------------------------------------------------------------------------
   title: Medical Dosage Calculator
   description: Safe medication dosage based on patient factors
   order: 5
   --------------------------------------------------------------------------

   Real-world example: Medical Dosage Calculator

   Use case: Calculate safe medication dosage based on patient weight,
   age, and medical conditions.

   Practical implications:
   - Ensures all dosage scenarios are properly handled
   - Identifies potential safety issues
   - Provides test cases for medical software validation
   - Helps verify compliance with medical guidelines
   - Critical for patient safety
*)

(* Dosage in mg *)
let calculate_adult_dosage weight_kg =
  if weight_kg < 40 then
    50
  else if weight_kg <= 60 then
    75
  else if weight_kg <= 80 then
    100
  else
    125

(* Age groups *)
let is_adult age = age >= 18
let is_child age = age >= 2 && age < 18
let is_infant age = age < 2

(* Calculate safe dosage *)
let calculate_dosage age weight_kg has_kidney_issues =
  if age < 0 || weight_kg <= 0 then
    (* Invalid input *)
    0
  else if age < 2 then
    (* Infants: 10mg regardless of weight *)
    10
  else if age < 18 then
    (* Children: weight-based, max 50mg *)
    let dose = weight_kg in
    if dose > 50 then 50 else dose
  else if has_kidney_issues then
    (* Adults with kidney issues: half dose *)
    let normal_dose = calculate_adult_dosage weight_kg in
    normal_dose / 2
  else
    (* Normal adults *)
    calculate_adult_dosage weight_kg
[@@decomp top ~basis:[[%id calculate_adult_dosage]] ()]

(* Variation: With pruning and contextual simplification *)
let calculate_dosage_safe age weight_kg has_kidney_issues =
  if age < 2 then
    10
  else if age < 18 then
    let dose = weight_kg in
    if dose > 50 then 50 else dose
  else if has_kidney_issues then
    let normal_dose = calculate_adult_dosage weight_kg in
    normal_dose / 2
  else
    calculate_adult_dosage weight_kg
[@@decomp top ~prune:true ~ctx_simp:true ~basis:[[%id calculate_adult_dosage]] ()]
