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": "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": [709, 843, 844]},
 {"title": "Netters Pediatrics (Florin Т., Ludwig St.)", "author": None, "pages": [265]},
 {"title": "Pediatric Pulmonology", "author": "American Academy of Pediatrics Section on Pediatric Pulmonology and Sleep Medicine;Michael J Light;Kristin Van Hook;", "pages": [144, 578, 579]},
 {"title": "Kliegman R. Nelson Textbook of Pediatrics 2-Volume Set 22ed 2024", "author": None, "pages": [2723]},
 {"title": "CURRENT Diagnosis and Treatment Pediatrics, Twenty-Fourth Edition", "author": "Hay, William W., Levin, Myron J., Deterding, Robin R., Abzug, Mark J.", "pages": [586]},
]

short_md = """## In short

- A pneumothorax is an abnormal accumulation of air in the pleural space, between the visceral and parietal pleura; it occurs more often in the neonatal period than at any other time of life, with an incidence of about 1-2% in term newborns and about 6% in premature infants.
- Classified as spontaneous (primary or secondary), traumatic, iatrogenic, tension, persistent, or (rarely) catamenial (thoracic endometriosis, occurring exclusively in reproductive-age women within 24-48 hours of menses onset, from air passing through diaphragmatic defects).
- Primary spontaneous pneumothorax occurs without trauma or known underlying lung disease, typically in tall, thin teenagers/young adults, more often male; apical blebs are often found on CT or at surgery, and connective tissue disorders (Marfan, Ehlers-Danlos syndromes) predispose to it. Smoking cigarettes, marijuana, crack cocaine, e-cigarette vaping, and MDMA use have been associated with its development.
- Secondary spontaneous pneumothorax complicates underlying lung disease: asthma, cystic fibrosis, congenital blebs/pneumatoceles/CPAMs, post-infectious disease (measles, PJP, TB, necrotizing pneumonia/abscess, echinococcal disease), interstitial lung disease (sarcoidosis, Langerhans cell histiocytosis), connective tissue disease, malignancy (lymphoma, metastasis), and aspiration (foreign body, meconium).
- Traumatic pneumothorax results from blunt or penetrating chest trauma or iatrogenic causes (mechanical ventilation/barotrauma, central line placement, intubation, endoscopy, transbronchial or percutaneous biopsy, laparoscopic procedures).
- Pathophysiology: increased intra-alveolar pressure causes alveolar rupture; air dissects along perivascular/fascial planes into the mediastinum and then breaks through the mediastinal pleura into the pleural space - the same mechanism can produce pneumomediastinum, pneumopericardium, pneumoperitoneum, and subcutaneous emphysema.
- In neonates, pneumothorax is often from positive pressure ventilation, excessive PEEP, or aggressive resuscitation, and is more common with surfactant deficiency or meconium aspiration; it can rapidly progress to a life-threatening tension pneumothorax.
- Pneumothorax is an uncommon asthma complication (0-3% incidence) but important during mechanical ventilation, and should be suspected with acute deterioration; associated pneumomediastinum occurs in 0-15% of children with asthma (bimodal peak at ages 4-6 and 13-18 years), with up to 30% of cases initially missed on radiography.
- Emergency decompression of a suspected tension pneumothorax in a neonate: needle/catheter decompression at the 4th intercostal space anterior axillary line or 2nd intercostal space midclavicular line, followed by chest tube (8F) placement.
"""

long_md = """## Definition

A pneumothorax is the accumulation of extrapulmonary air within the pleural space, between the visceral and parietal pleura. It can be static or progressively accumulating, and short- or long-term in duration. Because atmospheric pressure exceeds intrapleural pressure, any mechanism allowing communication between the atmosphere (or the tracheobronchial tree) and the pleural space can result in rapid air shift into that space.

## Epidemiology

Pneumothorax occurs more commonly in the neonatal period than at any other time of life, with an incidence of about 1-2% in term newborns and about 6% in premature infants. Beyond the neonatal period, pneumothoraces are uncommon in children overall but can be life-threatening. Data on exact pediatric incidence of spontaneous pneumothorax are limited, but it appears higher between ages 13 and 16 years. In children with asthma, pneumothorax is an uncommon complication (0-3% incidence), while pneumomediastinum occurs in 0-15% of cases with a bimodal age peak at 4-6 and 13-18 years.

## Etiology

Pneumothorax is broadly classified as spontaneous, traumatic, iatrogenic, or (rarely) catamenial. Primary spontaneous pneumothorax occurs without trauma or known underlying lung disease, typically in tall, thin (asthenic) teenagers and young adults, more often male; apical blebs of unknown cause are often found on CT or at surgery. Connective tissue disorders such as Marfan syndrome and Ehlers-Danlos syndrome predispose to primary spontaneous pneumothorax. Smoking cigarettes, marijuana, crack cocaine, e-cigarette vaping, and MDMA/ecstasy use have been associated with its development. Secondary spontaneous pneumothorax complicates an underlying disease process, including airway disease (asthma, cystic fibrosis), congenital structural abnormalities (blebs, pneumatoceles, congenital pulmonary airway malformations), post-infectious disease (measles, Pneumocystis jirovecii pneumonia, tuberculosis, necrotizing pneumonia or abscess, echinococcal parasitic disease), interstitial lung disease (sarcoidosis, Langerhans cell histiocytosis), connective tissue disease (Marfan syndrome, Ehlers-Danlos syndrome, rheumatoid arthritis, SLE, polymyositis, dermatomyositis), malignancy (lymphoma, metastasis), and aspiration (foreign body, meconium). Traumatic pneumothorax results from blunt or penetrating chest trauma, or from an iatrogenic cause: mechanical ventilation (barotrauma), central venous catheterization, airway procedures (intubation, endoscopy, transbronchial biopsy), laparoscopic procedures, or percutaneous biopsy. Catamenial pneumothorax (thoracic endometriosis) is a rare condition occurring exclusively in reproductive-age women, presenting as spontaneous pneumothorax within 24-48 hours of menstruation onset, thought to result from intra-abdominal air passing through diaphragmatic defects. Pneumothorax can also complicate pneumonia (usually with empyema), pulmonary abscess, gangrene, infarct, rupture of a cyst or emphysematous bleb (as in asthma), or an intrapulmonary foreign body; the incidence is relatively high in infants with staphylococcal pneumonia. In the neonatal period, pneumothorax often results from birth trauma, positive pressure ventilation, excessive PEEP, aggressive resuscitation, underlying obstructive/restrictive lung disease, or rupture of a congenital or acquired lung cyst, and is more common in premature infants with surfactant deficiency or in meconium aspiration.

## Pathophysiology

Increased intra-alveolar pressure causes alveolar rupture, releasing air into the interstitium; this interstitial air dissects along perivascular and fascial planes toward the mediastinum, then breaks through the mediastinal (or visceral) pleura to form a pneumothorax. In a ventilated infant, alveolar overdistention from injudicious distending pressure, or failure to wean ventilator pressure as lung compliance improves, is a common precipitant. The same dissection mechanism, with retrograde spread along bronchovascular bundles toward the hilum, can produce associated pneumomediastinum, pneumopericardium, pneumoperitoneum, and subcutaneous emphysema.

## Clinical Features

Presentation varies with the clinical setting. Term infants with a spontaneous pneumothorax may be asymptomatic or only mildly symptomatic, typically with tachypnea and mild oxygen needs early on, though they may progress to classic respiratory distress signs (grunting, flaring, retractions, tachypnea). Pneumothorax is a potentially lethal problem in neonates because of its capacity to progress rapidly to a tension pneumothorax. In children with asthma, pneumothorax should be suspected with acute deterioration, particularly during mechanical ventilation; the severity of an accompanying pneumomediastinum correlates with attack severity, but diagnosis requires a high index of suspicion since up to 30% of cases may initially be missed on radiography. Even small pneumothoraces in children may warrant admission for observation.

## Diagnostics

Diagnosis relies on clinical suspicion supported by imaging (chest radiograph, with CT sometimes needed to detect apical blebs in primary spontaneous pneumothorax). A high index of suspicion is needed in the setting of asthma exacerbation or acute deterioration on mechanical ventilation, since radiography can miss a substantial proportion of cases (up to 30% for associated pneumomediastinum).

## Treatment

Management depends on severity and underlying cause. In a neonate with significant respiratory distress and suspected pneumothorax, rapid decompression can be achieved with a large syringe, 20-gauge needle, or catheter-over-needle with a three-way stopcock, inserted at the fourth intercostal space in the anterior axillary line or the second intercostal space in the midclavicular line; a chest tube (8F) is then placed using standard technique. Even children with small pneumothoraces may require admission for observation given the risk of progression.

## Complications

Untreated or unrecognized pneumothorax, particularly in a neonate or a ventilated patient, can progress rapidly to tension pneumothorax, a life-threatening emergency. Associated air-leak phenomena (pneumomediastinum, pneumopericardium, pneumoperitoneum, subcutaneous emphysema) reflect the same underlying alveolar rupture and interstitial air dissection process and can accompany a pneumothorax, particularly in the neonatal and ventilated populations.
"""

clinical_md = """## Recognizing and Decompressing a Pneumothorax

In a neonate with respiratory distress - especially a premature infant with surfactant deficiency, a meconium aspiration history, or one receiving positive pressure ventilation or high PEEP - maintain a high suspicion for pneumothorax, since it can progress rapidly to a tension pneumothorax. For significant respiratory distress with suspected pneumothorax, decompress immediately with a large syringe, 20-gauge needle, or catheter-over-needle and three-way stopcock at the fourth intercostal space anterior axillary line or the second intercostal space midclavicular line, then place an 8F chest tube using standard technique. In a child with asthma who acutely deteriorates, particularly on mechanical ventilation, suspect pneumothorax or pneumomediastinum even without classic findings, since up to 30% of associated pneumomediastinum cases are initially missed on radiography - maintain a low threshold to repeat imaging or escalate care.

## Identifying the Underlying Cause

In a tall, thin adolescent male presenting with sudden chest pain and dyspnea without trauma, consider primary spontaneous pneumothorax and ask about smoking, vaping, or drug use (marijuana, cocaine, MDMA), and consider CT imaging for apical blebs if recurrence or diagnostic uncertainty exists; also consider an underlying connective tissue disorder (Marfan syndrome, Ehlers-Danlos syndrome) if there are supporting physical features or family history. In a child with known asthma, cystic fibrosis, or another chronic lung disease presenting with pneumothorax, classify it as secondary spontaneous pneumothorax and address the underlying disease alongside the acute air leak. Consider iatrogenic causes (recent central line placement, intubation, biopsy, or mechanical ventilation) in any hospitalized child who develops sudden respiratory decline. In an adolescent female with recurrent spontaneous pneumothorax temporally linked to menstruation, consider the rare diagnosis of catamenial pneumothorax and refer appropriately, since standard management alone will not address the underlying diaphragmatic defect. Even a small, seemingly stable pneumothorax in a child should prompt admission for observation given its potential to progress.
"""

build_and_save(
    topic="Pneumothorax",
    slug="pneumothorax",
    category_id=15560,
    summary="Pediatric pneumothorax: spontaneous (primary vs secondary) vs traumatic/iatrogenic classification, neonatal incidence and tension-pneumothorax risk, and needle/chest-tube decompression technique.",
    references=references,
    short_md=short_md,
    long_md=long_md,
    clinical_md=clinical_md,
)
