import sys, os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from lib import build_and_save

references = [
 {"title": "2021_Fleisher_&_Ludwig's_Textbook_of_Pediatric_Emergency_Medicine.epub", "author": None, "pages": []},
 {"title": "Kliegman R. Nelson Textbook of Pediatrics 2-Volume Set 22ed 2024", "author": None, "pages": [563, 565, 576]},
 {"title": "Cover", "author": "Vitalsource Download", "pages": [881, 882, 6919]},
 {"title": "Pediatric Nutrition (Ronald E. Kleinman, Frank R. Greer)", "author": None, "pages": [962]},
 {"title": "Gomella's Neonatology: Management, Procedures, On-Call Problems, Diseases, and Drugs, Eighth Edition", "author": "Tricia Lacy Gomella, Fabien G. Eyal and Fayez Bany-Mohammed", "pages": [467]},
]

short_md = """## In short

- Metabolic acidosis occurs from a net gain of H+ ions or a net loss of bicarbonate (HCO3-); nonvolatile acid is eliminated renally, while volatile acid is eliminated by pulmonary ventilation.
- Acute common causes: diarrhea (stool bicarbonate loss), shock/lactic acidosis (dehydration, blood loss, sepsis, heart disease), and diabetic ketoacidosis (metabolic acidosis with hyperglycemia, glycosuria, and ketonuria).
- Basic work-up: BUN, creatinine, glucose, urinalysis, and electrolytes; the anion gap helps differentiate causes.
- Starvation-related ketosis usually causes only mild acidosis (bicarbonate typically above 18 mEq/L); most children with ketosis and metabolic acidosis from poor intake actually have a concurrent illness (e.g., gastroenteritis with diarrhea) explaining the acidosis.
- Inborn errors of metabolism cause acidosis via excess ketoacids, lactic acid, or other organic anions, often episodically during acute decompensation triggered by specific dietary intake, mild illness, or poor treatment compliance - some patients have chronic acidosis instead; accompanying hypoglycemia or hyperammonemia can occur, and acidosis with seizures or depressed sensorium in an infant should raise suspicion for an inborn error.
- Chronic causes to consider: renal insufficiency, renal tubular acidosis (RTA; type II RTA occurs as part of Fanconi syndrome, with normoglycemia and glycosuria), and adrenal insufficiency (acidosis plus hypoglycemia); failure to thrive suggests a chronic process.
- Clinical manifestations vary with severity and cause and may include tachypnea (respiratory compensation), abdominal pain, vomiting, lethargy, neurologic abnormalities, and failure to thrive; severe metabolic acidosis can cause altered level of consciousness.
- Chronic metabolic acidosis produces reversible growth failure and, in CKD, treatment (bicarbonate or citrate supplementation) is particularly important for growth and bone health; chronic acidosis from bicarbonate loss responds well to daily bicarbonate added to feeds.
- IV sodium bicarbonate bolus for severe acidosis is generally unproven and risky, especially in small infants, where it can cause volume overload, intracranial hemorrhage, hypernatremia, respiratory acidosis, decreased oxygen delivery (increased hemoglobin-oxygen affinity), and paradoxical intracellular acidosis; it should be reserved for severely unstable, acidotic infants when other measures fail and only when ventilation can adequately clear the resulting CO2.
"""

long_md = """## Definition

Metabolic acidosis occurs when there is either a net gain of hydrogen (H+) ions or a net loss of bicarbonate (HCO3-) ions. Physiologic acids fall into two classes: volatile acids, eliminated through pulmonary ventilation, and nonvolatile acids, eliminated through renal excretion. The cardinal laboratory feature is reduced bicarbonate on blood gas or reduced serum carbon dioxide on electrolytes.

## Etiology

The cause is often apparent from history and physical exam. Acute causes commonly include diarrhea (from stool bicarbonate losses) and shock producing lactic acidosis (from dehydration, acute blood loss, sepsis, or heart disease). Diabetic ketoacidosis is suggested by metabolic acidosis together with hyperglycemia, glycosuria, and ketonuria. Starvation causes ketosis, but resulting acidosis, when present, is usually mild (bicarbonate typically above 18 mEq/L); most children with ketosis and metabolic acidosis from poor oral intake have a concomitant illness, such as gastroenteritis with diarrhea, that actually explains the acidosis. Inborn errors of metabolism can cause metabolic acidosis through excess production of ketoacids, lactic acid, or other organic anions, sometimes with accompanying hypoglycemia or hyperammonemia; acidosis in these disorders is often episodic, precipitated by specific dietary substrates, the stress of mild illness, or poor adherence to dietary/medical therapy, though a minority of inborn errors cause chronic acidosis. Adrenal insufficiency can cause metabolic acidosis with hypoglycemia, as can liver failure. Type II renal tubular acidosis (RTA) as part of Fanconi syndrome produces metabolic acidosis with normoglycemia and glycosuria, from impaired proximal tubular glucose resorption. Chronic causes more broadly include renal insufficiency and RTA, and should be suspected when failure to thrive is present. New-onset polyuria suggests previously undiagnosed diabetes mellitus/DKA. A variety of prescribed or accidentally ingested medications and toxins can cause metabolic acidosis; identifying a toxic ingestion such as ethylene glycol or methanol is especially important given the potential for excellent response to specific antidotal therapy. Hepatomegaly with metabolic acidosis can be seen in sepsis, congenital or acquired heart disease, hepatic failure, or inborn errors of metabolism. In dehydration, metabolic acidosis may result from stool bicarbonate losses (diarrhea), secondary acute kidney injury, or lactic acidosis from shock, while emesis or nasogastric losses more typically cause metabolic alkalosis instead. In chronic kidney disease, metabolic acidosis arises either from primary renal tubular damage (with a normal anion gap) or from retained phosphate/sulfate anions as uremia worsens (an increased anion gap).

## Clinical Features

Clinical manifestations are variable and depend on underlying etiology and severity; children may be asymptomatic or present with tachypnea (respiratory compensation), abdominal pain, vomiting, lethargy, neurologic abnormalities, or failure to thrive. In mild-to-moderate acidosis, most signs and symptoms actually reflect the underlying disorder rather than the acidemia itself. Severe metabolic acidosis (as with severe dehydration) can produce an altered level of consciousness; concurrent electrolyte disturbances (sodium, calcium, magnesium, phosphorus abnormalities) can compound neurologic effects, and severe dehydration alone can cause profound lethargy even without significant electrolyte derangement. Metabolic acidosis with seizures or a depressed sensorium, especially in an infant, should raise concern for an underlying inborn error of metabolism, while meningitis and sepsis with lactic acidosis are more common explanations for acidosis accompanied by neurologic signs generally.

## Diagnostics

Basic laboratory evaluation includes BUN, serum creatinine, serum glucose, urinalysis, and serum electrolytes, with the anion gap used to help differentiate among causes. History should cover duration and presence of diarrhea, polyuria, and growth failure; physical exam should assess perfusion and growth parameters. Serum potassium interpretation is complicated in dehydration: diarrheal and urinary potassium losses (plus metabolic alkalosis from emesis) can cause hypokalemia, while metabolic acidosis (which shifts potassium out of cells) and acute kidney injury can cause hyperkalemia - multiple mechanisms may coexist, making the resulting acid-base and potassium status difficult to predict from history alone.

## Treatment

Treatment centers on correcting the underlying pathophysiology to reduce acid production or restore bicarbonate, rather than simply normalizing pH. Fluid balance should be corrected in infants with a dilutional component. Chronic metabolic acidosis from ongoing bicarbonate loss responds well to daily bicarbonate supplementation added to feedings, and in chronic kidney disease, treatment with supplemental bicarbonate or citrate solutions is particularly important for growth and bone health. Acute intravenous sodium bicarbonate bolus infusion has commonly been used for severe, persistent metabolic acidosis, but this approach is generally unproven and carries meaningful risk, particularly in small infants: volume overload, intracranial hemorrhage, hypernatremia, respiratory acidosis, decreased capillary oxygen exchange (from increased hemoglobin-oxygen affinity), and paradoxical intracellular acidosis as the bicarbonate reacts with water to generate carbon dioxide that diffuses into cells. This treatment should be reserved for severely unstable, acidotic infants when other measures fail, and only when the infant is intubated and ventilated, or breathing well enough spontaneously, to readily lower PCO2.

## Complications / Outcome

Chronic metabolic acidosis produces reversible growth failure. Outcomes from acute, severe metabolic acidosis are usually determined by the underlying cause itself, or by complications of overly aggressive treatment with sodium bicarbonate bolus infusions, rather than the acidosis alone.
"""

clinical_md = """## Working Up a Child with Metabolic Acidosis

Obtain BUN, creatinine, glucose, urinalysis, and electrolytes as baseline studies, and calculate the anion gap to narrow the differential. In an acutely ill child, consider diarrhea (stool bicarbonate loss), shock/lactic acidosis (assess perfusion carefully - dehydration, blood loss, sepsis, and heart disease can all present this way), and DKA (check glucose, urine ketones and glucose) as the most common acute causes. In a child with ketosis and only mild acidosis (bicarbonate above 18 mEq/L) attributed to poor intake, actively look for a concurrent illness such as gastroenteritis, since starvation ketosis alone rarely explains significant acidosis. Treat metabolic acidosis with seizures or depressed sensorium in an infant as a possible inborn error of metabolism until proven otherwise, checking for accompanying hypoglycemia or hyperammonemia, while considering meningitis/sepsis with lactic acidosis as the more common explanation when neurologic signs and acidosis coexist without a metabolic-disease history. In a child with failure to thrive and chronic acidosis, evaluate for renal insufficiency or renal tubular acidosis, including Fanconi syndrome-associated type II RTA (normoglycemia with glycosuria) and adrenal insufficiency (acidosis with hypoglycemia). Always ask about medication exposure and possible toxic ingestion (ethylene glycol, methanol), since these are treatable causes with excellent response to specific therapy when identified promptly.

## Treating Metabolic Acidosis Safely

Direct treatment first at correcting the underlying cause - rehydration and treatment of the precipitating illness, rather than bicarbonate, resolves most cases. Correct fluid balance in infants with a dilutional component to their acidosis. For chronic acidosis from ongoing bicarbonate loss, add bicarbonate supplementation directly to feeds. Avoid reflexive intravenous sodium bicarbonate bolus for acute acidosis: reserve it for severely unstable, persistently acidotic infants who have failed other measures, and only when the infant is intubated/ventilated or breathing well enough spontaneously to clear the resulting CO2 load, given the risks of volume overload, intracranial hemorrhage, hypernatremia, worsened respiratory acidosis, impaired oxygen delivery, and paradoxical intracellular acidosis. Counsel families that chronic acidosis causes reversible growth failure, and that adequate correction (for example, in chronic kidney disease with bicarbonate or citrate) is important specifically for growth and bone health, not simply for normalizing a lab value.
"""

build_and_save(
    topic="Metabolic Acidosis",
    slug="metabolic-acidosis",
    category_id=14933,
    summary="Pediatric metabolic acidosis: distinguishing acute (diarrhea, shock, DKA) from chronic (RTA, renal insufficiency, inborn errors) causes, the anion-gap work-up, and why bicarbonate bolus therapy is risky and reserved for last resort.",
    references=references,
    short_md=short_md,
    long_md=long_md,
    clinical_md=clinical_md,
)
