"""Place Daniel's Respiratory Failure article over the generated stub at /articles/264."""
import uuid
from datetime import datetime

from app.database import SessionLocal
from app.models.article import Article
from app.services import article_service

LONG = [
("Introduction and definitions", """Respiratory failure remains one of the leading causes of morbidity, intensive care unit admission, and cardiopulmonary arrest in the pediatric population. Unlike adults, in whom cardiac dysrhythmias are the predominant trigger for arrest, pediatric cardiac arrest is overwhelmingly the terminal consequence of progressive respiratory failure or shock. Early identification and targeted physiological intervention are therefore paramount.

Respiratory failure occurs when the respiratory system cannot adequately satisfy the metabolic demands of the body regarding arterial oxygenation, carbon dioxide elimination, or both. Clinically and gasometrically, it is generally defined by:

- **Hypoxemia**: arterial partial pressure of oxygen (PaO2) < 60 mmHg on room air, or SpO2 < 90% despite supplemental low-flow oxygen.
- **Hypercapnia**: arterial partial pressure of carbon dioxide (PaCO2) > 50 mmHg accompanied by respiratory acidosis (pH < 7.30), unless compensated chronically."""),

("Why children decompensate faster", """Children possess unique structural and functional differences that predispose them to rapid decompensation:

- **Airway geometry**: the pediatric airway is narrower and has higher resistance (Poiseuille's law states resistance is inversely proportional to the radius to the fourth power, R ∝ 1/r⁴). A single millimeter of mucosal edema drastically increases work of breathing.
- **Chest wall mechanics**: highly cartilaginous and compliant ribs offer poor structural support, leading to paradoxical inward movement during negative inspiratory pressure generation, and inefficient tidal volume generation.
- **Functional residual capacity (FRC)**: FRC is closer to closing capacity in infants, predisposing dependent lung zones to microatelectasis during normal tidal breathing.
- **Metabolic rate**: oxygen consumption in neonates and young children is 6–8 mL/kg/min, roughly double that of adults, leading to rapid desaturation during hypoventilation or apnea.
- **Diaphragmatic composition**: pediatric diaphragms possess fewer fatigue-resistant Type I (slow-twitch) fibers, predisposing young children to rapid muscle fatigue."""),

("Type 1: hypoxemic respiratory failure (lung failure)", """Type 1 failure is characterized by a low PaO2 with a normal or decreased PaCO2 secondary to tachypnea. The underlying pathophysiology typically involves ventilation–perfusion (V/Q) mismatching, intrapulmonary shunting, or impaired alveolar–capillary diffusion.

**Etiologies.** Severe viral [[3|bronchiolitis]] (e.g. RSV), bacterial or viral [[150|pneumonia]], pediatric acute respiratory distress syndrome (PARDS), cardiogenic and non-cardiogenic pulmonary edema, and [[166|cyanotic congenital heart disease]].

**Pathophysiology.** Alveolar flooding, inflammation, and atelectasis prevent oxygen diffusion into the pulmonary capillary bed despite adequate ventilatory effort. True intrapulmonary shunt — complete alveolar consolidation, for instance — fails to correct completely with high fractions of inspired oxygen (FiO2) alone and necessitates positive end-expiratory pressure (PEEP)."""),

("Type 2: hypercapnic respiratory failure (pump failure)", """Type 2 failure is defined by alveolar hypoventilation resulting in carbon dioxide retention (PaCO2 > 50 mmHg with acidemia). Hypoxemia invariably coexists if the patient breathes room air, but it readily corrects with low levels of supplemental oxygen, unmasking the primary ventilatory defect.

**Etiologies.** Central nervous system depression (head trauma, [[315|seizures]], intoxication, central hypoventilation), neuromuscular disorders (spinal muscular atrophy, Guillain–Barré syndrome, botulism), thoracic wall deformities, and late-stage muscular exhaustion from severe upper or lower airway obstruction — [[133|status asthmaticus]], critical croup.

**Pathophysiology.** Decreased minute ventilation (minute ventilation = tidal volume × respiratory rate) or increased dead-space ventilation (Vd/Vt) leads directly to CO2 accumulation, according to the alveolar ventilation equation."""),

("Type 3: perioperative / atelectatic respiratory failure", """Often considered a subset of Type 1, this form occurs secondary to anesthesia, operative positioning, systemic opiate analgesia, and splinting from abdominal or thoracic incisional pain. The reduction in functional residual capacity promotes baseline basilar collapse, loss of lung compliance, and subsequent V/Q mismatch."""),

("Type 4: shock-induced (hypoperfusion) respiratory failure", """In states of circulatory shock — [[178|septic]], cardiogenic, or [[211|hypovolemic]] — the respiratory muscles demand an excessive fraction of the total cardiac output (up to 40%, against less than 5% at baseline) to sustain compensatory hyperventilation for metabolic acidosis. Intubation and mechanical ventilation in this setting are implemented primarily to offload metabolic work from the diaphragm and redirect critical perfusion to vital organs."""),

("Distress versus failure", """Distinguishing between respiratory distress and true respiratory failure is critical for timely escalation of therapy.

**Respiratory distress (compensated).** Maintained gas exchange via increased physiological work. Tachypnea, subcostal, intercostal and suprasternal retractions, nasal flaring, grunting (physiologic auto-PEEP generation), and tachycardia. Blood gas analysis often demonstrates respiratory alkalosis (low PaCO2) with normal oxygenation.

**Respiratory failure (decompensated).** Inability to sustain compensatory mechanisms. Bradypnea or irregular respirations, head bobbing, profound lethargy, altered mental status, see-saw (abdominal paradox) breathing, central cyanosis, and a "pseudonormal" or elevated PaCO2 in an exhausted, tachypneic patient."""),

("Diagnostic workup", """Management must never be delayed for diagnostic testing in an unstable child, but objective evaluation refines therapy.

- **Arterial or venous blood gas**: evaluates pH, PaCO2, and base deficit. Venous gases adequately reflect pH and PaCO2 (usually 4–6 mmHg higher than arterial); arterial sampling is the gold standard for assessing exact PaO2 and calculating the PaO2/FiO2 ratio or oxygenation index.
- **Continuous pulse oximetry and capnography**: waveform capnography gives real-time information on alveolar ventilation, airway obstruction (prolonged expiratory upstroke), and early identification of respiratory arrest.
- **Point-of-care ultrasound**: rapidly differentiates consolidation, [[396|pneumothorax]] (absence of lung sliding, barcode sign), pleural effusion, and pulmonary interstitial fluid (B-lines).
- **Chest radiography**: delineates focal infiltrates, hyperinflation, cardiomegaly, or air-leak syndromes once the patient is physiologically stabilized."""),

("Management: airway, oxygen and support", """**Airway stabilization.** Positioning is crucial: place children younger than two years in a neutral "sniffing" position using an occipital roll to avoid neck flexion caused by a prominent occiput. Clear secretions with gentle suctioning, especially in infants with viral [[3|bronchiolitis]].

**High-flow nasal cannula (HFNC).** Heated, humidified gas blends at flows typically titrated from 1 to 2 L/kg/min (up to 60 L/min in older children). HFNC washes out anatomical nasopharyngeal dead space, improving alveolar ventilation; provides modest, flow-dependent positive distending airway pressure (approximately 2–5 cmH2O); and reduces inspiratory resistance and the metabolic work of conditioning dry, cold ambient air.

**Non-invasive positive pressure ventilation (NIV).** CPAP and BiPAP are indicated for moderate-to-severe Type 1 and Type 2 failure, before exhaustion occurs.

- *CPAP* (typically 5–8 cmH2O) maintains continuous airway pressure throughout the respiratory cycle, stenting open microatelectatic alveoli, increasing FRC, and improving V/Q matching in Type 1 failure.
- *BiPAP* (IPAP 10–14 cmH2O, EPAP 5–8 cmH2O) adds an inspiratory pressure over the baseline expiratory pressure, directly assisting tidal volume generation to unload fatigued inspiratory muscles and clear CO2 in Type 2 failure.
- *Contraindications*: cardiac arrest, unmanaged [[396|pneumothorax]], severe facial trauma, inability to protect the airway with absent gag reflex, or persistent vomiting."""),

("Management: invasive ventilation", """Endotracheal intubation is indicated for refractory hypoxemia (failure of NIV or HFNC), worsening severe hypercapnic acidosis, acute clinical exhaustion, depressed airway reflexes, or hemodynamic instability requiring critical resuscitation.

**Clinical pearl.** Cuffed endotracheal tubes are now universally recommended in pediatric practice, sized by formulas such as (age / 4) + 3.5 for cuffed tubes. They ensure lower leak rates, reliable end-tidal monitoring, and accurate tidal volume delivery without increasing the risk of subglottic stenosis when cuff pressures are maintained below 20 cmH2O.

Ventilator management should prioritize lung-protective ventilation:

- Target low tidal volumes, 5–7 mL/kg of ideal body weight.
- Limit plateau pressures below 28–30 cmH2O.
- Optimize PEEP to restore FRC while avoiding dynamic alveolar hyperinflation.
- Accept permissive hypercapnia (pH > 7.20–7.25), provided there is no elevated intracranial pressure, pulmonary arterial hypertension, or significant myocardial dysfunction."""),

("Management: etiology-specific pharmacotherapy", """- **Bronchospasm**: inhaled short-acting beta-2 agonists (albuterol), anticholinergics (ipratropium bromide), early systemic corticosteroids (dexamethasone, methylprednisolone), and intravenous magnesium sulfate or terbutaline for severe refractory [[133|status asthmaticus]].
- **Croup and subglottic edema**: nebulized racemic epinephrine, or L-epinephrine 1:1,000, and oral, intramuscular or intravenous dexamethasone 0.6 mg/kg.
- **Infection**: targeted antimicrobials based on the suspected source — broad-spectrum beta-lactams and macrolides for community-acquired [[150|pneumonia]], for instance.
- **CNS or toxin depression**: immediate administration of specific reversal agents when indicated, such as naloxone for suspected opiate-induced hypoventilation."""),
]

SHORT = [
("Definitions", """- ==PaO2 < 60 mmHg on room air== (or SpO2 < 90% on low-flow oxygen) — hypoxemic failure.
- ==PaCO2 > 50 mmHg with pH < 7.30== — hypercapnic failure, unless chronically compensated.
- Pediatric arrest is ==the terminal consequence of respiratory failure or shock==, not of dysrhythmia."""),

("The four types", """- **Type 1, lung failure**: V/Q mismatch, shunt, diffusion defect. Bronchiolitis, pneumonia, PARDS, pulmonary edema, cyanotic heart disease. ==True shunt does not correct with FiO2 alone — it needs PEEP.==
- **Type 2, pump failure**: alveolar hypoventilation. CNS depression, neuromuscular disease, chest wall deformity, ==exhaustion at the end of severe obstruction==. Hypoxemia corrects readily with a little oxygen.
- **Type 3, perioperative**: anesthesia, positioning, opiates, splinting → ==FRC falls, basilar collapse==.
- **Type 4, shock**: respiratory muscles take ==up to 40% of cardiac output==; intubation offloads the diaphragm."""),

("Distress or failure", """- Distress is ==compensated==: tachypnea, retractions, flaring, grunting, respiratory alkalosis.
- Failure is ==decompensated==: bradypnea, head bobbing, see-saw breathing, lethargy, cyanosis.
- ==A "normal" PaCO2 in an exhausted tachypneic child is a rising one.=="""),

("Numbers worth carrying", """- Oxygen consumption in the young child: ==6–8 mL/kg/min==, about double the adult.
- HFNC ==1–2 L/kg/min==, giving ==2–5 cmH2O== of distending pressure.
- CPAP ==5–8 cmH2O==; BiPAP ==IPAP 10–14 / EPAP 5–8==.
- Cuffed tube size ==(age / 4) + 3.5==, cuff pressure ==under 20 cmH2O==.
- Lung protection: ==Vt 5–7 mL/kg== ideal body weight, ==plateau < 28–30 cmH2O==, permissive hypercapnia to ==pH > 7.20–7.25==."""),
]

CLINICAL = [
("At the bedside: the escalation ladder", """1. **Position and clear.** Neutral "sniffing" position with an occipital roll under two years; gentle suction, especially in bronchiolitis.
2. **HFNC**, 1–2 L/kg/min. Dead-space washout, 2–5 cmH2O of distending pressure, less work conditioning the gas.
3. **NIV before exhaustion.** CPAP 5–8 cmH2O for hypoxemic failure; BiPAP IPAP 10–14 / EPAP 5–8 to unload the muscles and clear CO2.
4. **Intubate** for refractory hypoxemia, worsening hypercapnic acidosis, exhaustion, depressed airway reflexes, or hemodynamic instability.

Do not use NIV in cardiac arrest, unmanaged pneumothorax, severe facial trauma, an unprotected airway with absent gag, or persistent vomiting."""),

("At the bedside: after the tube", """Cuffed tube, size (age / 4) + 3.5, cuff pressure kept under 20 cmH2O.

Set for lung protection from the first breath: tidal volume 5–7 mL/kg of ideal body weight, plateau pressure under 28–30 cmH2O, PEEP titrated to restore FRC without hyperinflation, and permissive hypercapnia down to pH 7.20–7.25 — unless there is raised intracranial pressure, pulmonary hypertension, or myocardial dysfunction."""),

("At the bedside: treat the cause", """- **Bronchospasm**: albuterol, ipratropium, early systemic steroid; magnesium sulfate or terbutaline if refractory.
- **Croup**: nebulized racemic or L-epinephrine, dexamethasone 0.6 mg/kg by any route.
- **Infection**: source-directed antimicrobials.
- **Opiate or toxin depression**: naloxone, and the specific antidote where one exists.

In shock, remember that the ventilator is a circulatory intervention: it takes the work of breathing away from a diaphragm that is competing with the vital organs for cardiac output."""),
]

SUMMARY = ("Respiratory failure is oxygenation or CO2 clearance that no longer meets metabolic demand, and in children it is "
           "the road to cardiac arrest. Four types — hypoxemic lung failure, hypercapnic pump failure, perioperative "
           "atelectasis, and the shock state that steals cardiac output for the diaphragm — with an escalation ladder from "
           "position and suction, through HFNC and NIV, to lung-protective invasive ventilation.")

INTRO = ("""Written for the ward and the exam: what respiratory failure is, why a child reaches it faster than an adult, how the four types differ in what they do to the blood gas, and what to do about each of them.

*By Daniel Onyejesi — pediatric critical care.*""")


def build(rows, variant):
    out = []
    for title, content in rows:
        out.append({
            "id": uuid.uuid4().hex,
            "slug": title.lower().replace(":", "").replace(",", "").replace("(", "").replace(")", "")
                         .replace("/", "-").replace(" ", "-")[:120].strip("-"),
            "title": title,
            "variant": variant,
            "content": content.strip(),
        })
    return out


db = SessionLocal()
article = db.get(Article, 264)
print("before:", article.title, article.status, len(article.sections or []), article.generated_by)

# Keep what was there. The generated stub becomes a revision rather than being
# thrown away, so the swap is reversible from the article's own history.
article_service.snapshot(db, article, user_id=6, note="Replaced the generated draft with Daniel's article")

article.title = "Pediatric Respiratory Failure"
article.summary = SUMMARY
article.content = INTRO
article.sections = build(SHORT, "short") + build(LONG, "long") + build(CLINICAL, "clinical")
article.references_json = [{"title": "Kliegman R. Nelson Textbook of Pediatrics", "author": None, "pages": []}]
article.generated_by = None
article.generated_at = None
article.user_id = 6
article.status = "published"
if article.first_published_at is None:
    article.first_published_at = datetime.utcnow()
db.commit()
article_service.reindex(db, article)
print("after:", article.title, article.status, len(article.sections), "sections")
print("variants:", article_service.available_variants(article))
