///|
fn rank_parts(letter : Char, number : Int) -> Int {
  (letter.to_string().to_upper()[0].to_int() - ('A' : UInt16).to_int()) * 100 +
  number
}

///|
fn rank_code(code : String) -> Int {
  let c = compact_code(code)
  match c.get_char(0) {
    Some(letter) =>
      match parse_two_digits(c, at=1) {
        Some(number) => rank_parts(letter, number)
        None =>
          match c.get_char(1) {
            Some(second) if is_digit_char(second) && c.length() >= 3 =>
              rank_parts(letter, digit_value(c[1]) * 10 + 9)
            _ => -1
          }
      }
    None => -1
  }
}

///|
pub fn icd10_chapters() -> Array[IcdChapter] {
  [
    {
      id: "I",
      title: "Certain infectious and parasitic diseases",
      start: "A00",
      end: "B99",
      note: "Includes intestinal infectious diseases and viral infections.",
    },
    {
      id: "II",
      title: "Neoplasms",
      start: "C00",
      end: "D49",
      note: "Neoplasms by site and behavior.",
    },
    {
      id: "III",
      title: "Diseases of the blood and immune mechanism",
      start: "D50",
      end: "D89",
      note: "Blood, blood-forming organs, and immune disorders.",
    },
    {
      id: "IV",
      title: "Endocrine, nutritional and metabolic diseases",
      start: "E00",
      end: "E89",
      note: "Endocrine glands, nutrition, and metabolic disorders.",
    },
    {
      id: "V",
      title: "Mental, Behavioral and Neurodevelopmental disorders",
      start: "F01",
      end: "F99",
      note: "Mental health and neurodevelopmental coding range.",
    },
    {
      id: "VI",
      title: "Diseases of the nervous system",
      start: "G00",
      end: "G99",
      note: "Central, peripheral, and episodic nervous system disorders.",
    },
    {
      id: "VII",
      title: "Diseases of the eye and adnexa",
      start: "H00",
      end: "H59",
      note: "Eye and adnexa diseases.",
    },
    {
      id: "VIII",
      title: "Diseases of the ear and mastoid process",
      start: "H60",
      end: "H95",
      note: "Ear and mastoid process diseases.",
    },
    {
      id: "IX",
      title: "Diseases of the circulatory system",
      start: "I00",
      end: "I99",
      note: "Heart, blood vessel, and cerebrovascular diseases.",
    },
    {
      id: "X",
      title: "Diseases of the respiratory system",
      start: "J00",
      end: "J99",
      note: "Upper and lower respiratory tract diseases.",
    },
    {
      id: "XI",
      title: "Diseases of the digestive system",
      start: "K00",
      end: "K95",
      note: "Mouth, gastrointestinal tract, liver, gallbladder, and pancreas.",
    },
    {
      id: "XII",
      title: "Diseases of the skin and subcutaneous tissue",
      start: "L00",
      end: "L99",
      note: "Skin and subcutaneous tissue disorders.",
    },
    {
      id: "XIII",
      title: "Diseases of the musculoskeletal system and connective tissue",
      start: "M00",
      end: "M99",
      note: "Bones, joints, muscles, and connective tissue.",
    },
    {
      id: "XIV",
      title: "Diseases of the genitourinary system",
      start: "N00",
      end: "N99",
      note: "Urinary and reproductive system disorders.",
    },
    {
      id: "XV",
      title: "Pregnancy, childbirth and the puerperium",
      start: "O00",
      end: "O9A",
      note: "Pregnancy and childbirth coding range.",
    },
    {
      id: "XVI",
      title: "Certain conditions originating in the perinatal period",
      start: "P00",
      end: "P96",
      note: "Perinatal conditions.",
    },
    {
      id: "XVII",
      title: "Congenital malformations and chromosomal abnormalities",
      start: "Q00",
      end: "Q99",
      note: "Congenital and chromosomal coding range.",
    },
    {
      id: "XVIII",
      title: "Symptoms, signs and abnormal findings",
      start: "R00",
      end: "R99",
      note: "Symptoms and abnormal clinical/lab findings.",
    },
    {
      id: "XIX",
      title: "Injury, poisoning and external causes",
      start: "S00",
      end: "T88",
      note: "Trauma, poisoning, and selected complications.",
    },
    {
      id: "XX",
      title: "External causes of morbidity",
      start: "V00",
      end: "Y99",
      note: "Accidents, exposures, and external causes.",
    },
    {
      id: "XXI",
      title: "Factors influencing health status",
      start: "Z00",
      end: "Z99",
      note: "Encounters, status, and health service factors.",
    },
    {
      id: "XXII",
      title: "Codes for special purposes",
      start: "U00",
      end: "U85",
      note: "Special purpose and provisional coding.",
    },
  ]
}

///|
pub fn find_chapter(code : IcdCode) -> IcdChapter? {
  icd10_chapters()
  .search_by(fn(chapter) { chapter.contains(code) })
  .map(fn(i) { icd10_chapters()[i] })
}

///|
pub fn chapters_for_range(start : String, end : String) -> Array[IcdChapter] {
  let low = rank_code(start)
  let high = rank_code(end)
  icd10_chapters().filter(fn(chapter) {
    let c_low = rank_code(chapter.start)
    let c_high = rank_code(chapter.end)
    c_low <= high && c_high >= low
  })
}