"""Two more of Daniel's: high-frequency ventilation physics, and the mole concept."""
import uuid
from datetime import datetime

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


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


def upsert(db, slug, title, summary, intro, sections, category_id=None):
    existing = db.query(Article).filter(Article.slug == slug).first()
    article = existing or Article(slug=slug)
    article.title = title
    article.summary = summary
    article.content = intro
    article.sections = sections
    article.references_json = [{"title": "Kliegman R. Nelson Textbook of Pediatrics", "author": None, "pages": []}]
    article.category_id = category_id
    article.user_id = 6
    article.status = "published"
    article.first_published_at = article.first_published_at or datetime.utcnow()
    if not existing:
        db.add(article)
    db.commit()
    db.refresh(article)
    article_service.reindex(db, article)
    return article


HFV_SHORT = [
("The two equations", """- **Oxygenation = MAP + FiO2.** Mean airway pressure holds the lung open; ==everything that raises MAP raises oxygenation==.
- **CO2 clearance ∝ frequency × VT².** ==Amplitude is squared, so it is the heavy knob: double ΔP and you roughly quadruple CO2 removal.==
- The whole point of high-frequency ventilation is that these two are ==decoupled==. On a conventional ventilator PIP moves both."""),

("The ten rules", """1. ==Oxygenation is mean airway pressure.== Keep the lung open with MAP and FiO2.
2. ==Ventilation is amplitude² × frequency.== Shake the CO2 out, ΔP first.
3. ==ETT forces, nasal prongs assist.== The seal decides who is in control.
4. ==Flow delivers, diffusion exchanges.== You only have to get fresh gas to the alveolar doorstep.
5. CO2 is fast because it is ==soluble==, not because it is light — Fick at the membrane, not Graham.
6. Tiny volumes work because ==transport and transfer are different jobs==: convection carries, diffusion crosses.
7. ==HFJV needs a background ventilator; HFOV is self-contained.==
8. To lower CO2 on HFOV, raise ΔP — and note that ==lowering the frequency often helps==, because each slower cycle carries a bigger VT.
9. ==Watch the chest wiggle==, not a tidal volume number: the displayed VT does not mean what it means in SIMV.
10. ==Sedation matters more in HFV.== A baby fighting the oscillator defeats it; in SIMV you want spontaneous effort."""),

("Why the squared law keeps appearing", """Transport per cycle scales with ==how much gas moves × how far it moves==, and both scale with VT — so transport goes as VT². It is the same arithmetic as kinetic energy (==½mv²==), electrical power (==I²R==) and a spring (==½kx²==): the same quantity appears in the push and in the distance.

The clinical trap: ==raising the frequency shortens each cycle and shrinks VT==, and because VT is squared, the loss can outweigh the gain."""),
]

HFV_LONG = [
("The question this answers", """High-frequency ventilation delivers breaths *smaller than the dead space*, hundreds of times a minute, and somehow clears CO2 better than a conventional breath. That should be impossible: if every puff is smaller than the tubing it has to cross, no fresh gas ever reaches an alveolus.

The resolution is that bulk flow is not how gas crosses the last third of a millimetre, and that a gas shaken back and forth in a tube does not simply return to where it started. What follows builds the mechanism from the wall of the airway outward."""),

("The no-slip condition, and the parabolic profile", """When gas flows through a tube, the layer touching the wall does not move at all. Friction holds it — the no-slip condition — and each layer drags the next, so velocity climbs from zero at the wall to a maximum in the centre:

> **v(r) = v_max · (1 − r²/R²)**

Gas therefore never travels as a solid piston. It *smears*: the centre streaks ahead while the wall lingers. This one fact is the physical basis of every streaming and mixing mechanism in high-frequency ventilation."""),

("Dwell time: why the wall layer is the dirty lane", """Because wall-layer gas barely moves, it spends the longest time next to the gas-exchange region — and time is exactly what diffusion needs. CO2 diffuses into it. The fast central gas passes too quickly to pick much up.

The wall layer is CO2-rich because it dwells longest, not because there is anything special about the wall. Dwell time is the whole of the explanation."""),

("Why oscillation alone does nothing", """Here is the step that is usually skipped. Shake gas back and forth in a tube in which the concentration is *radially uniform*, and the net transport is exactly zero. Every molecule goes forward and comes back. Perfect symmetry, nothing accumulates.

So the mechanism cannot be "the breaths are fast". Nor can it be that expiration is passive and slower: the parabolic profile has the same shape in both directions, and passive expiration changes its magnitude, not its shape. The proof is clinical — HFOV *actively* pulls gas out on expiration and HFJV lets it fall out passively, and the same streaming happens in both."""),

("What breaks the symmetry: radial sorting", """By the time each cycle reverses, the gas has been sorted across the radius:

- **Centre = fresh.** It arrived fast and has not had time to exchange.
- **Wall = spent.** It has dwelled, and has loaded CO2 by diffusion.

Now the parabolic profile has something to act on. On inspiration the fresh centre wins the race inward. On expiration everything moves outward — including the central gas — but the spent gas is the one occupying the slow peripheral lane, and it is the gas you want to leave.

Averaged over a cycle, the centre lane has net inward displacement and the wall lane net outward displacement. Two streams, opposite directions, the same tube, at the same time.

**The principle worth keeping:** the velocity gradient is the engine; the radial concentration gradient is the steering wheel. Oscillation alone transports nothing. Oscillation plus a radial concentration gradient transports directionally. In physics this is **Taylor dispersion** — axial convection with a velocity gradient interacting with radial diffusion to produce a net axial transport far larger than either alone.

At HFOV frequencies of 5–15 Hz this becomes literal rather than merely cycle-averaged: the near-wall layer lags so far behind the pressure that it can be moving outward while the core is still moving inward. That is Womersley flow, and it is two actual lanes in the same instant."""),

("The two-zone rule: flow delivers, diffusion exchanges", """The lung is two physically different regions, and conflating them is what makes sub-dead-space ventilation seem impossible.

| Zone | Anatomy | How gas moves | Exchange |
|---|---|---|---|
| Conducting | Trachea → terminal bronchioles, ~16 generations | Convection: bulk flow and streaming | None. Pure plumbing. |
| Respiratory | Respiratory bronchioles → alveolar ducts → alveoli | Diffusion; flow velocity ≈ 0 | O2 and CO2 across the membrane |

You do not need bulk flow *inside* an alveolus. You need flow to keep fresh gas at the doorstep, and the last 0.2–0.3 mm is crossed by diffusion, which over microscopic distances is nearly instantaneous.

Diffusion time scales as t ∝ x²/D. Across one alveolus, x ≈ 0.2 mm = 2×10⁻⁴ m, and D for CO2 ≈ 1.6×10⁻⁵ m²/s:

> **t ≈ (2×10⁻⁴)² / 1.6×10⁻⁵ ≈ 0.0025 s — about 2.5 milliseconds.**

With zero flow inside the alveolus, CO2 equilibrates in a couple of milliseconds. Diffusion is not the bottleneck; getting fresh gas into the neighbourhood is, and that is the job streaming does."""),

("Why the story is always told in CO2", """Both gases cross the membrane by diffusion. CO2 dominates the account for three reasons.

**Solubility, not molecular weight.** Graham's law — rate ∝ 1/√MW — governs diffusion *through a gas*, and by it O2 (MW 32) is slightly faster than CO2 (MW 44). But the alveolar membrane is a water and tissue barrier, so Fick's law governs: flux ∝ solubility × ΔP / thickness. CO2 is 20–24 times more soluble in water and tissue, so it crosses roughly 20 times faster. "CO2 diffuses fast" is true, and it is true because of solubility.

**The arithmetic is lopsided.** Inspired CO2 is ~0 mmHg and alveolar CO2 ~40: the change is from nothing at all. Inspired O2 is ~150 mmHg and alveolar ~100: a 33% drop. The wall layer's CO2 enrichment is simply a louder signal.

**O2 is oversupplied.** We deliver 21–100% oxygen while the body consumes a fraction of each breath, so alveolar gas never gets used up the way it gets filled."""),

("The squared law, and why it recurs", """> **CO2 clearance ∝ frequency × VT²**

The single most important relationship in high-frequency ventilation, and the same shape as ½mv², I²R and ½kx². The reason the square keeps appearing is always the same: energy or transport is push × distance, and the same quantity sets both.

- A spring: force = kx *and* distance = x, so energy = ½kx².
- A circuit: voltage = IR *and* charge = It, so power = I²R.
- Oscillating gas: volume moved per cycle ∝ VT *and* the distance it is displaced ∝ VT, so transport per cycle ∝ VT².

Do that f times a minute and CO2 clearance ∝ f × VT².

**What follows clinically.** Amplitude is dominant because it is squared: double ΔP and CO2 removal roughly quadruples. Frequency matters less, and carries a trap — at a higher frequency each cycle is shorter, so VT shrinks, and because VT is squared the loss can outweigh the gain. Hence the counterintuitive HFOV rule: to blow off CO2, you often *lower* the frequency, from 12 Hz to 10, because the larger VT clears more."""),

("Decoupling: the entire point", """| | Conventional (SIMV) | High-frequency (HFJV/HFOV) |
|---|---|---|
| Oxygenation | FiO2 + PEEP/MAP | **FiO2 + MAP** |
| Ventilation | Rate + VT/PIP | **Amplitude (ΔP) + frequency** |
| Coupling | Knobs overlap — PIP moves both | **Fully decoupled** |

This is why high-frequency ventilation rescues lungs conventional ventilation cannot: you can open the lung with a high mean pressure for oxygenation without also inflating and deflating it through a large tidal excursion. That is protection from volutrauma and barotrauma, which is precisely what an air-leak syndrome such as pulmonary interstitial emphysema needs."""),

("The four modes, side by side", """| | SIMV | NIMV / NIPPV | HFJV | HFOV |
|---|---|---|---|---|
| Interface | ETT, sealed in trachea | Nasal prongs or mask, leaky | ETT + jet adapter + background vent | ETT, dedicated oscillator circuit |
| Breath size | Normal VT, ~4–6 mL/kg | Normal VT | Tiny, below dead space | Tiny, below dead space |
| Rate | 20–60/min | 20–60/min | 240–420/min (4–7 Hz) | 300–900/min (5–15 Hz) |
| Expiration | Passive | Passive | Passive | **Active** — the piston pulls out |
| Can it force a breath? | Yes | Assists only; leak limits it | Yes | Yes |
| CO2 knob | Rate + VT/PIP | Rate + PIP | Amplitude (jet PIP) + rate | Amplitude (ΔP) + frequency |
| O2 knob | FiO2 + PEEP/MAP | FiO2 + PEEP/MAP | FiO2 + PEEP from background vent | FiO2 + MAP |
| Classic use | Routine invasive ventilation | Step-down, avoiding intubation | Air leak (PIE), rescue | Air leak, severe RDS, rescue |"""),

("Why the interface decides everything", """**With an endotracheal tube** — SIMV, HFJV, HFOV — the tube is sealed in the trachea, so set pressure is close to delivered pressure and the machine can truly force a breath: the gas has nowhere to go but into the lungs.

**Without one** — NIMV, NIPPV — the interface leaks, around the prongs, around the mask, out of the mouth. Two consequences follow. Delivered pressure is lower than set, and variable. And resistance in narrow prongs and tubing loses more pressure on the way. You therefore often set a higher pressure and flow than you actually want, to compensate.

Can NIMV force a breath? Not reliably. The baby can open their mouth, cry, or simply not accept the inflation. NIMV *assists* the baby's own breathing; it does not commandeer it. NCPAP is continuous pressure with no breaths at all — the baby does all the work. NIPPV, and sNIPPV when synchronised, is CPAP with intermittent pressure peaks: the baby breathes, the machine boosts.

One line to keep: **ETT means the machine is in control; prongs mean the machine assists.**"""),

("Every knob, and what it moves", """**Conventional**

| Knob | What it is | What it controls |
|---|---|---|
| FiO2 | Oxygen fraction, 0.21–1.0 | Oxygenation |
| PEEP | Baseline pressure at end-expiration | Keeps alveoli open → MAP → oxygenation |
| PIP | Peak inspiratory pressure | Tidal volume → ventilation |
| VT | Tidal volume, mL/kg | Ventilation |
| Rate | Breaths per minute | Ventilation |
| Ti | Inspiratory time | Breath delivery, MAP, I:E |
| I:E | Inspiratory : expiratory time | Gas trapping, MAP |
| Flow | Gas delivery speed | Breath shape, how fast PIP is reached |
| Rise time | Time to peak pressure | Comfort, synchrony |
| Trigger | Effort needed to fire a breath | Synchrony |
| Pressure support | Extra pressure on spontaneous breaths | Reduces the baby's work |
| Volume guarantee | Target VT; the machine adjusts PIP | Auto-weans pressure to hold VT |

**High-frequency**

| Knob | What it is | What it controls |
|---|---|---|
| MAP | Mean airway pressure | **Oxygenation** — recruitment |
| Amplitude (ΔP) | Size of the oscillation, the "wiggle" | **CO2** — the dominant knob |
| Frequency (Hz) | Oscillations per second | **CO2** — secondary, and tricky |
| Bias flow (HFOV) | Continuous fresh gas through the circuit | Flushes CO2 while the piston oscillates |
| PEEP + sigh (HFJV) | From the background ventilator | Recruitment, sets the baseline MAP |"""),

("The background ventilator, and why HFJV needs one", """HFJV — the Bunnell Life Pulse, for instance — is never used alone. It is excellent at high-frequency puffs and poor at two things: holding a steady PEEP, and giving occasional recruiting sigh breaths. So it runs in tandem with a conventional ventilator in a simple CPAP mode.

A special triple-lumen tube, or a LifePort adapter, carries all three jobs: lumen one takes the jet's high-frequency puffs, lumen two takes the conventional ventilator providing PEEP and sighs, lumen three is the pressure monitoring port. The conventional ventilator supplies PEEP of perhaps 5–8 cmH2O — the baseline MAP holding the lung open — plus sigh breaths, maybe 2–10 a minute at a slightly higher PIP, to re-recruit. The jet's puffs ride on top, so the actual MAP is the PEEP plus the average contribution of the puffs.

The conventional ventilator is the platform; the jet is the engine. HFOV, by contrast, sets its own MAP directly and needs no background ventilator."""),
]

HFV_CLINICAL = [
("Turning the knobs", """**To improve oxygenation:** raise MAP, or raise FiO2. On HFOV, MAP is a knob of its own; on HFJV it comes from the background ventilator's PEEP plus the jet's contribution.

**To lower CO2:** raise the amplitude first. It is squared, so it is by far the heaviest lever — roughly four times the clearance for twice the ΔP. If that is not enough, consider *lowering* the frequency: a slower cycle carries a larger tidal volume, and the squared term rewards that more than the extra cycles would have.

**To raise CO2** (rarely wanted, but sometimes it is): drop the amplitude.

**What to watch.** The chest wiggle, not the displayed tidal volume — in high-frequency modes that number does not mean what it means in SIMV. And keep the baby settled: a child fighting the oscillator defeats the mode, which is the opposite of SIMV, where spontaneous effort is welcome."""),

("Choosing the mode", """- **SIMV** for routine invasive ventilation, where you want the baby's own effort and a normal tidal volume.
- **NIMV / NIPPV** to step down, or to avoid intubation. Remember it assists rather than commands: a leak means the pressure you set is not the pressure delivered.
- **HFJV** for air leak — pulmonary interstitial emphysema in particular — and for rescue. It needs a background ventilator for PEEP and sighs.
- **HFOV** for air leak, severe RDS, and rescue. Self-contained, with active expiration."""),
]

MOLE_SHORT = [
("What to remember", """- A mole is the bridge between ==the atomic scale and the laboratory scale==: it turns a number of particles into a mass you can weigh.
- The atomic mass unit is ==1/12th the mass of a carbon-12 atom==.
- Avogadro's number is ==6.022 × 10²³== particles per mole.
- So ==one mole of carbon atoms weighs 12 g and contains 6.022 × 10²³ atoms==.
- Avogadro's hypothesis: ==equal volumes of gases at the same temperature and pressure contain equal numbers of particles.=="""),
]

MOLE_LONG = [
("Introduction", """The mole concept is a cornerstone of modern chemistry, bridging the gap between the microscopic world of atoms and molecules and the macroscopic world of laboratory measurements. It allows measurable masses to be related to the invisible world of particles, which is what makes chemical reactions and calculations practical."""),

("Alchemy", """Alchemy, the precursor to modern chemistry, involved the transformation of substances and precise measurement during experiments such as distillation. The alchemists' observations of patterns and relationships in matter laid the groundwork for atomic theory and, eventually, for the mole."""),

("John Dalton and atomic theory", """John Dalton proposed that all matter is made of atoms, and that atoms of the same element are identical in mass and properties. Atoms distinguished the elements, and compounds were combinations of different atoms.

Dalton did not recognise that atoms could exist as molecules, which led to incorrect formulae — HO for water, for instance."""),

("Gay-Lussac and the gas laws", """Joseph Gay-Lussac discovered that gases react in simple volume ratios: two litres of hydrogen with one litre of oxygen produce two litres of water vapour. The observation suggested a simple relationship between the numbers of reacting particles, but Dalton's atomic theory could not explain the volume changes."""),

("Avogadro's hypothesis", """Amadeo Avogadro explained Gay-Lussac's findings by proposing that equal volumes of gases, at the same temperature and pressure, contain equal numbers of particles. That clarified why the number of particles — and so the volume — decreases in reactions such as the formation of water from hydrogen and oxygen. Avogadro also recognised that elements could exist as molecules rather than as single atoms."""),

("The atomic mass unit and Avogadro's number", """The atomic mass unit is defined as one twelfth of the mass of a carbon-12 atom, which lets chemists express atomic and molecular masses consistently.

Since atoms and molecules cannot be weighed individually, the mole relates atomic mass units to grams. Avogadro's number, 6.022 × 10²³, is the number of particles in one mole of a substance. One mole of carbon atoms weighs 12 grams and contains 6.022 × 10²³ atoms."""),

("Summary", """- The mole concept connects the atomic scale to the laboratory scale.
- Alchemy, Dalton, Gay-Lussac and Avogadro each contributed to its development.
- The atomic mass unit and Avogadro's number let chemists measure and calculate quantities of substances in practical terms."""),
]

db = SessionLocal()

hfv = upsert(
    db, "high-frequency-ventilation-physics",
    "High-Frequency Ventilation: How It Actually Works",
    ("Why breaths smaller than the dead space clear CO2 better than normal ones: the no-slip condition, the parabolic "
     "velocity profile, radial sorting of fresh and spent gas, and Taylor dispersion. Then the two equations that run "
     "the bedside — oxygenation from mean airway pressure, CO2 from frequency × amplitude² — and the four modes, their "
     "interfaces and every knob on them."),
    """Oscillation alone moves nothing. What makes a high-frequency ventilator work is that the gas in an airway is not radially uniform — and this is the chain of physics from the wall of the tube to the knob under your thumb.

*By Daniel Onyejesi — neonatal and pediatric critical care.*""",
    build(HFV_SHORT, "short") + build(HFV_LONG, "long") + build(HFV_CLINICAL, "clinical"),
    category_id=14876)
print("hfv:", hfv.id, hfv.slug, len(hfv.sections), article_service.available_variants(hfv))

mole = upsert(
    db, "the-mole-concept",
    "The Mole Concept: Foundations and Historical Development",
    ("How chemistry learned to count particles by weighing them: from the alchemists' measurements through Dalton's "
     "atoms and Gay-Lussac's volume ratios to Avogadro's hypothesis, the atomic mass unit, and 6.022 × 10²³."),
    """The bridge between the microscopic world of atoms and the macroscopic world of the balance, and the people who built it.

*By Daniel Onyejesi — medical education.*""",
    build(MOLE_SHORT, "short") + build(MOLE_LONG, "long"))
print("mole:", mole.id, mole.slug, len(mole.sections), article_service.available_variants(mole))
