"""Five diagrams into the bank, and into the articles they explain.

Drawn as SVG rather than generated as pictures: these are schematics, so what
matters is that every label is exactly right and stays right at any size — and
a diagram assembled from shapes can be corrected by editing a line. A generated
raster of a "radiograph" would also be a fabrication dressed as evidence, which
is the one thing a teaching figure must never be.

Each one goes in as a media asset with a title, a description and a source, so
it behaves like every other figure: a thumbnail in the prose, the full view on
a click, and findable in the library by what it shows.
"""
import pathlib

from app.database import SessionLocal
from app.models.article import Article
from app.models.media import MediaAsset
from app.services import article_service, embedding_service, storage_service

FIGURES = [
    {
        "file": "salter-harris.svg",
        "slug": "pediatric-fracture-eponyms",
        "section": "salter-harris-the-classification-masterwork",
        "title": "Salter-Harris types I to V",
        "alt": "Five schematics of a growth plate, each with the fracture line of one Salter-Harris type.",
        "caption": ("The five Salter-Harris types side by side: through the physis (I), with a "
                    "metaphyseal corner (II), into the joint through the epiphysis (III), across "
                    "all three zones (IV), and a crush of the germinal layer (V)."),
    },
    {
        "file": "parabolic-profile.svg",
        "slug": "high-frequency-ventilation-physics",
        "section": "the-no-slip-condition-and-the-parabolic-profile",
        "title": "The parabolic profile, and the two lanes it creates",
        "alt": "A cross-section of an airway: velocity arrows longest in the centre and zero at the wall, with fresh gas shaded in the middle and spent gas at the edges.",
        "caption": ("Velocity is zero at the wall and greatest in the centre, so fresh gas races "
                    "down the middle while the wall layer dwells and loads CO₂. Oscillate that and "
                    "the two lanes travel in opposite directions at once."),
    },
    {
        "file": "two-zone-lung.svg",
        "slug": "high-frequency-ventilation-physics",
        "section": "the-two-zone-rule-flow-delivers-diffusion-exchanges",
        "title": "Flow delivers, diffusion exchanges",
        "alt": "A branching airway on the left labelled conducting zone, alveoli on the right labelled respiratory zone.",
        "caption": ("Sixteen generations of plumbing, then a region where flow has stopped and "
                    "diffusion does the work. It is why a breath smaller than the dead space can "
                    "still clear CO₂: flow only has to reach the doorstep."),
    },
    {
        "file": "respiratory-failure-types.svg",
        "slug": "respiratory-failure",
        "section": "type-1-hypoxemic-respiratory-failure-lung-failure",
        "title": "The four types of respiratory failure",
        "alt": "Four panels: lung failure, pump failure, perioperative atelectasis, and shock.",
        "caption": ("What each type does to the blood gas, and what causes it — the lung failing, "
                    "the pump failing, the functional residual capacity falling after surgery, and "
                    "the diaphragm competing with the organs for cardiac output."),
    },
    {
        "file": "mole-bridge.svg",
        "slug": "the-mole-concept",
        "section": "the-atomic-mass-unit-and-avogadros-number",
        "title": "One atom, one mole, one weighable mass",
        "alt": "Three panels joined by arrows: 12 amu for one carbon-12 atom, 6.022 × 10²³ particles in a mole, 12 grams on the balance.",
        "caption": ("The bridge the mole is: an atomic mass unit is a twelfth of a carbon-12 atom, "
                    "Avogadro's number is how many particles make a mole, and the two together are "
                    "why one mole of carbon weighs twelve grams."),
    },
]

SOURCE = "Schematic drawn for PedsHub."

db = SessionLocal()
here = pathlib.Path("/tmp/figs")

for figure in FIGURES:
    data = (here / figure["file"]).read_bytes()
    key = f"figures/{figure['file']}"
    storage_service.save(key, data, "image/svg+xml")

    asset = db.query(MediaAsset).filter(MediaAsset.path == key).first() or MediaAsset(path=key)
    asset.title = figure["title"]
    asset.alt_text = figure["alt"]
    asset.caption = figure["caption"]
    asset.source = SOURCE
    asset.kind = "image"
    asset.byte_size = len(data)
    asset.storage = "s3" if storage_service.using_s3() else "local"
    asset.user_id = 6
    if asset.id is None:
        db.add(asset)
    db.commit()
    db.refresh(asset)
    try:
        if embedding_service.embed_record(asset, "media"):
            db.commit()
    except Exception:
        db.rollback()

    article = db.query(Article).filter(Article.slug == figure["slug"]).first()
    if not article:
        print(f"no article {figure['slug']}")
        continue
    sections = article.sections or []
    target = next((s for s in sections if s.get("slug") == figure["section"]), None)
    if target is None:
        print(f"  ? {figure['slug']}: no section {figure['section']} — sections are "
              f"{[s.get('slug') for s in sections][:6]}")
        continue
    mark = f"![{figure['alt']}](/uploads/{key})"
    if mark in (target.get("content") or ""):
        print(f"  = already in {figure['slug']} › {target['title']}")
        continue
    rebuilt = []
    for section in sections:
        copy = dict(section)
        if copy.get("slug") == figure["section"]:
            copy["content"] = f"{mark}\n\n{copy.get('content') or ''}".strip()
        rebuilt.append(copy)
    article.sections = rebuilt
    db.commit()
    db.expire(article)
    stuck = any(mark in (s.get("content") or "") for s in (article.sections or []))
    article_service.reindex(db, article)
    print(f"  {'+' if stuck else '!'} {figure['title']} → {article.title} › {target['title']}")
