#!/usr/bin/env python3
# Book 21 (Apollo Hospitals) — THE HOUSE THAT HEALS. Science->business: the human BODY is a
# system (the heart PUMPS, the lungs BREATHE, the blood CARRIES) -> a hospital MIRRORS the body
# (many specialists as one system, scans that see inside, an emergency room like the body's alarm)
# -> the great house of healing whose moat is trusted doctors, a hard-to-copy network and scale,
# so long as its care stays affordable and kind.
import os
ART="/root/omahaindia.com/comics/site/book/apollo/art"
OUT="/root/omahaindia.com/comics/site/book/apollo/index.html"
STYLE=("children's storybook manga illustration, warm painted animation style, soft cinematic light, "
"clean linework, NO text NO letters NO words")
CHARLOTTE=("Charlotte, the SAME young Indian CHILD girl from the reference, round young face, warm tan skin, "
"freckles, glossy black hair in two low twin ponytails, big curious dark eyes, bright TEAL t-shirt, NO facial hair")
GRAHAM="Ben, a kind scholarly elderly American gentleman, round wire spectacles, tweed suit and bow tie"
BUFFETT="Warren, a folksy cheerful elderly American man, thinning white hair, big friendly glasses, grey suit"
MUNGER="Charlie, a stocky wise elderly American man, very thick black-framed glasses, dark suit"
IRIS=("Iris, a warm friendly Western DOCTOR, NOT Indian, calm reassuring smile, short silver-streaked hair, "
"a crisp white coat over teal scrubs, a stethoscope around her neck")

# name -> (w,h,seed,prompt,ref). ref set -> Seedream character; None -> flux scene. Ritual panels copied by mkbook.
NEW={
 "00_cover":(1024,1180,1600,f"{STYLE}. BOOK COVER, {CHARLOTTE} standing with {IRIS} at the bright welcoming doors of a great hospital that glows softly like a living body, holding up a gently pulsing red model heart that beats with warm light, a golden sunrise behind, wonder, cinematic","charlotte"),
 "_ref_iris":(1024,1024,1601,f"{STYLE}. clean friendly character portrait, {IRIS}, plain soft warm background, calm smile, head and shoulders",None),
 # Ch1
 "ap_c1_coin":(1024,720,1610,f"{STYLE}. {CHARLOTTE} at home, Grandpa Ben's glowing brass compass twitching between a little red toy heart and a tiny model hospital on the table, EXPRESSION puzzled and intrigued, cozy lamp light","charlotte"),
 "ap_c1_diary":(1024,720,1611,f"{STYLE}. an open magical diary glowing warm gold on a desk, a faint ribbon of light rising from the page and curling into a tiny beating heart shape, no people",None),
 "ap_c1_swirl":(1024,720,1612,f"{STYLE}. {CHARLOTTE} pulled into a swirling spiral of golden light and soft red-and-teal ribbons from a glowing diary, EXPRESSION thrilled, magical","charlotte"),
 # Ch2 — arrive at the hospital, meet Iris
 "ap_c2_arrive":(1024,720,1613,f"{STYLE}. {CHARLOTTE} landing wide-eyed at the bright glass doors of an enormous friendly hospital, tall clean towers rising into a blue sky, EXPRESSION awe and delight, bright daylight","charlotte"),
 "ap_c2_iris":(1024,720,1614,f"{STYLE}. {IRIS} warmly welcoming {CHARLOTTE} in the hospital lobby, gently resting a hand on her shoulder, EXPRESSION Charlotte shy happy smile; keep the SAME doctor from the reference, same white coat, same teal scrubs, same stethoscope","iris"),
 "ap_c2_pit":(1024,720,1615,f"{STYLE}. a vast bright hospital atrium seen from above, many clean corridors and wards branching out, tiny doctors and nurses hurrying calmly along them for scale, powerful and reassuring, no faces close up",None),
 # Ch3 — the heart is a pump
 "ap_c3_leaf":(1024,720,1616,f"{STYLE}. {IRIS} kneeling to show {CHARLOTTE} a glowing red model of a beating heart cupped in her hands, a tiny pulse of light inside it, EXPRESSION Charlotte fascinated leaning in; SAME doctor, white coat, teal scrubs, stethoscope","iris"),
 "ap_c3_forest":(1024,720,1617,f"{STYLE}. a giant friendly glowing heart squeezing like a gentle fist, warm rivers of red blood flowing out along branching tubes, magical and alive, soft red light, no people",None),
 "ap_c3_store":(1024,720,1618,f"{STYLE}. a friendly close up of a heart pump squeezing and relaxing, pushing a little wave of red blood onward like a water pump, playful science, no people",None),
 # Ch4 — the lungs breathe
 "ap_c4_sink":(1024,720,1619,f"{STYLE}. {CHARLOTTE} watching in wonder as a pair of soft pink lungs fill up with sparkling fresh air like two gentle balloons, EXPRESSION amazed and thoughtful, airy blue light","charlotte"),
 "ap_c4_press":(1024,720,1620,f"{STYLE}. a magical cutaway of a chest showing air flowing down into two pink lungs and tiny golden sparkles of fresh air passing into the red blood beside them, gentle arrows of breath, warm glow, no people",None),
 "ap_c4_rock":(1024,720,1621,f"{STYLE}. a beautiful close up inside a lung, tiny round air pockets like clusters of soft bubbles handing bright golden air-sparkles to little red blood boats, dreamy and clean, no people",None),
 # Ch5 — the blood carries
 "ap_c5_burn":(1024,720,1622,f"{STYLE}. cheerful little red blood cell boats sailing along a glowing vessel, each carrying a bright golden bubble of air and a parcel of food to deliver, warm and busy, no people",None),
 "ap_c5_boil":(1024,720,1623,f"{STYLE}. {IRIS} showing {CHARLOTTE} a glowing map of the body's blood rivers reaching into every fingertip and toe, EXPRESSION Charlotte delighted 'aha'; SAME doctor, white coat, teal scrubs, stethoscope","iris"),
 # Ch6 — scans that see inside; many specialists as one system
 "ap_c6_spin":(1024,720,1624,f"{STYLE}. {CHARLOTTE} watching a big friendly scanning machine light up a glowing screen that reveals the gentle glowing bones and organs inside a body, EXPRESSION awed and curious, calm bright room","charlotte"),
 "ap_c6_electric":(1024,720,1625,f"{STYLE}. a hospital glowing softly like a living body, many warm points of light — a heart room, a lung room, a bone room — all connected by gentle threads of light into one system, magical, no faces close up",None),
 # Ch7 — the emergency room, the body's alarm; care for everyone
 "ap_c7_everyone":(1024,720,1626,f"{STYLE}. a busy but caring emergency room glowing warm at night, an ambulance with soft flashing lights arriving at the doors, kind teams ready to help, hopeful, no faces close up",None),
 "ap_c7_half":(1024,720,1627,f"{STYLE}. a warm storybook scene of a single hospital caring for everyone — a tiny newborn, a child, a grown-up, a gentle grandparent — all safe under one glowing roof, tender togetherness, no faces close up",None),
 # Ch8 — reveal Apollo Hospitals
 "ap_c8_reveal":(1024,720,1628,f"{STYLE}. {CHARLOTTE} and {IRIS} standing proudly before a great gleaming modern hospital glowing against a blue sky, EXPRESSION proud recognition; SAME doctor, white coat, teal scrubs, stethoscope","charlotte"),
 "ap_c8_1975":(1024,720,1629,f"{STYLE}. warm sepia 1980s scene, the very first big modern hospital of its kind opening its doors, hopeful doctors and gleaming new machines, families arriving with hope, inspiring, no text",None),
 "ap_c8_scale":(1024,720,1630,f"{STYLE}. many gleaming modern hospitals of one family standing across a sunny land, linked by glowing threads of care, the biggest network of healing houses, proud and grand, no people",None),
 # Ch10 (ch9 uses ritual castle/invert/verdict; ch10 uses ritual wake/diary)
 "ap_c10_look":(1024,720,1631,f"{STYLE}. {CHARLOTTE} outside at dusk looking with wonder at the people passing by — each one carrying a quietly beating heart and breathing lungs — as if she can see the gentle glow of life inside everyone, EXPRESSION delighted wonder","charlotte"),
}

def P(img,cap=None,b1=None,b2=None,sfx=None,sfxc="#e8425a",tall=False): return ("panel",img,cap,b1,b2,sfx,sfxc,tall)
def SUB(d,t): return ("sub",d,t)
def WOW(t): return ("wow",t)
def NOTE(t,b): return ("note",t,b)
def TL(r): return ("timeline",r)
def MOAT(c): return ("moat",c)

CHAPTERS=[
 ("c1","CHAPTER 1","The Beat That Wouldn't Stop","pages 1-8",[
   P("ap_c1_coin","Back home, Grandpa Ben's compass twitched again — pointing between a little red toy heart and a tiny model of a great building.","A heart… and a big building? What's the link?",None,"twitch"),
   P("ap_c1_diary","The old diary fell open. A new line shimmered in Grandpa Ben's hand.",None,'"Find the marvellous machine you carry inside you — and the house built to mend it."'),
   WOW("A tiny heart and a huge building don't seem to belong together — yet inside YOU is a machine more wonderful than any factory, and people built whole houses just to care for it. What is the marvel hiding inside your own chest? That's the puzzle of this whole adventure."),
   P("ap_c1_swirl","Golden light swirled up and pulled Charlotte in.","Here we GO!",None,"WHOOSH","#1f9c8f"),
   NOTE("Charlotte's Secret Notebook","Two BIG questions:<br>➊ What is the wonderful machine beating inside me right now?<br>➋ Grandpa Ben says there's a whole <i>house</i> built to heal it. How does a house mirror a body? 🫀"),
 ]),
 ("c2","CHAPTER 2","The Great House of Healing","pages 9-16",[
   P("ap_c2_arrive","One blink, and she stood before the biggest, cleanest, kindest building she'd ever seen — tall bright towers full of light.","It's a whole CITY of care!"),
   P("ap_c2_iris","A doctor in a white coat smiled warmly. \"I'm Iris. In here we look after the most amazing machine in the world — the human body.\"","The most amazing… MACHINE?!"),
   P("ap_c2_pit","Through the doors, corridors branched off like rivers — wards, scanning rooms, an operating theatre — all humming gently.","So many rooms — and they all work together?","Stick with me, kiddo."),
   NOTE("Charlotte's Secret Notebook","Iris is a doctor, and she grins like she has a secret — just like the other guides did. She calls the body 'the most amazing machine'. Okay Iris… show me how it works! ✨"),
 ]),
 ("c3","CHAPTER 3","The Little Pump Inside You","pages 17-26",[
   P("ap_c3_leaf","Iris cupped a glowing model heart. \"Feel your chest. That thump-thump is a little pump, squeezing all day and all night — it never takes a break.\"","A pump — inside ME, right now!"),
   P("ap_c3_forest","\"Every squeeze pushes red blood out along tubes that branch to every single part of you.\"","It sends blood EVERYWHERE!"),
   P("ap_c3_store","\"Squeeze… rest… squeeze… rest. About once every second, your whole life long.\"","My heart has been pumping this WHOLE time!",None,"thump","#e8425a"),
   WOW("Here's the first secret! 💗 Your <b>heart</b> is a tireless little <b>pump</b>. Each squeeze pushes red blood out through branching tubes to reach every corner of your body — and it does this about once a second, day and night, without ever stopping to rest."),
   ("diagram",),
   NOTE("Charlotte's Secret Notebook","The heart is a pump. Every squeeze sends red blood along tubes to every part of the body. It beats about once a second, all day and all night, forever. 🫀"),
 ]),
 ("c4","CHAPTER 4","The Bellows of Breath","pages 27-36",[
   P("ap_c4_sink","\"But the blood needs something first,\" said Iris. \"Take a big breath.\" Two soft lungs filled up like balloons.","In goes the air — puff!"),
   P("ap_c4_press","\"Your lungs catch fresh air, and hand its goodness — a gas called oxygen — straight over to the blood flowing past.\"","The lungs give the air to the blood!",None,"breathe","#1f9c8f"),
   P("ap_c4_rock","\"Inside each lung are millions of tiny air pockets, passing little sparks of fresh air to little red boats of blood.\"","So THAT'S why we breathe!"),
   WOW("Your <b>lungs</b> are a pair of gentle bellows. When you breathe in, they catch fresh air and hand its <b>oxygen</b> to the blood rushing past. That's why a body needs BOTH: lungs to fetch the air, and a heart to pump the blood that carries it."),
   NOTE("Charlotte's Secret Notebook · SOLVED (part 1)","Lungs breathe in fresh air and pass its oxygen to the blood. The heart then pumps that blood around. Lungs fetch the air; the heart delivers it! 🫁"),
 ]),
 ("c5","CHAPTER 5","The Rivers That Carry","pages 37-44",[
   P("ap_c5_burn","\"The blood is the delivery service,\" Iris said. Tiny red boats sailed along, each carrying air and food.","Little boats — carrying parcels!",None,"sail","#e8425a"),
   P("ap_c5_boil","\"These rivers reach every fingertip and toe, dropping off air and food and carrying away the rubbish. No corner is ever forgotten.\"","Blood feeds the WHOLE body?"),
   WOW("Your <b>blood</b> is a busy river of little red boats. It <b>carries</b> oxygen from the lungs and food from your meals to every single part of you, and carries the waste away. Heart, lungs and blood are a team — a pump, a pair of bellows, and a delivery service."),
   NOTE("Charlotte's Secret Notebook","Blood carries oxygen and food to every part of the body and takes the waste away. The heart PUMPS it, the lungs FILL it with air, the blood CARRIES it. A team! 🩸"),
 ]),
 ("c6","CHAPTER 6","Eyes That See Inside","pages 45-52",[
   P("ap_c6_spin","Iris led her to a giant machine. It glowed, and a screen lit up — showing the bones and organs INSIDE a body, without a single cut.","We can SEE inside — like magic!"),
   P("ap_c6_electric","\"And no one doctor knows everything,\" said Iris. \"A heart doctor, a lung doctor, a bone doctor — all working together, like the parts of the body itself.\"","Many experts — one team!"),
   WOW("A hospital <b>mirrors the body</b>. Special machines called <b>scans</b> let doctors see inside without hurting you. And just as the heart, lungs and blood work as one system, <b>many specialists</b> — each an expert in one part — work together as one team to heal the whole person."),
   NOTE("Charlotte's Secret Notebook · SOLVED!","Scanners let doctors see inside the body safely. And many different specialists team up — heart, lung, bone, brain — working as ONE system, just like the parts of a body. 🔬"),
 ]),
 ("c7","CHAPTER 7","The Body's Alarm Bell","pages 53-60",[
   P("ap_c7_everyone","A siren glowed softly in the night as an ambulance pulled in. Doctors and nurses rushed to help, calm and ready.","When something goes wrong — they're READY!"),
   P("ap_c7_half","\"An emergency room is like your body's alarm bell,\" said Iris. \"When something hurts, help comes — for a tiny baby, a child, a grandparent, anyone.\"","Everyone can be cared for here!"),
   WOW("Your body has its own <b>alarm</b> — pain, that tells you when something is wrong. A hospital's <b>emergency room</b> is that alarm made real: day or night, when someone is hurt or sick, a ready team comes to help. And a great house of healing opens its doors to <b>everyone.</b>"),
   NOTE("Charlotte's Secret Notebook","Pain is the body's alarm. The emergency room is the hospital's alarm — always ready, day and night, to help anyone who is hurt or sick. Babies, children, grandparents — everyone. 🚑"),
 ]),
 ("c8","CHAPTER 8 · THE BIG DISCOVERY","The House With Many Rooms","pages 61-70",[
   P("ap_c8_reveal","Iris led Charlotte to a viewpoint over the gleaming hospital and all its wings.","Who built ALL of this?"),
   P("ap_c8_1975","\"In 1983,\" said Iris, \"one of India's first big modern hospitals of this kind opened its doors, with the best machines and the finest care.\"","One great house, built with hope!"),
   P("ap_c8_scale","\"It grew and grew — into a whole family of hospitals across the land, healing millions.\"","From ONE house… to a whole network!"),
   WOW("A \"company\" can be a giant shared job of caring. <b>Apollo Hospitals</b> opened in 1983 as one of India's first big modern hospitals, and grew into a wide <b>network of healing houses</b> — bringing trusted doctors and costly machines to millions of people."),
   TL([("1983","India's first big modern hospital of its kind opens its doors."),
       ("Over decades","It grows into a whole network of hospitals across the land."),
       ("Today","Its doctors and machines heal millions of people every year."),
       ("Tomorrow","It keeps care warm and affordable, so no one is ever left out. 🩺")]),
   NOTE("Charlotte's Secret Notebook","Apollo Hospitals (1983) was one of India's first big modern hospitals and grew into a whole NETWORK of healing houses, bringing trusted doctors and costly machines to millions. 🏥"),
 ]),
 ("c9","CHAPTER 9","The Castle Built on Care","pages 71-80",[
   P("ap_c9_castle","Two kind old men appeared with a glow. Warren pointed at a castle standing on a hill of gentle healing light. \"What keeps rivals out, Charlotte?\"","Walls! But what kind?"),
   MOAT([("🩺","Wall One: Trusted Doctors","People hand a hospital their very lives. That trust is earned patient by patient, year by year — and it cannot be copied overnight.",False),
         ("🏥","Wall Two: A Hard-to-Copy Network","Many hospitals woven together across the whole land, sharing doctors and know-how. A rival can't build so wide a web quickly.",False),
         ("🔬","Wall Three: The Scale to Buy Costly Machines","Great scanners and tools cost a fortune. Being big means it can afford the finest machines that smaller places simply cannot.",False),
         ("⚠️","The Crack in the Wall","Care must stay AFFORDABLE and KIND. If healing grows too costly or cold, people are left out — and a house of healing that forgets kindness loses the trust it was built on.",True)]),
   P("ap_c9_munger","Charlie tapped his head. \"Don't just ask how to WIN. Ask how you'd LOSE — then don't do that. Invert!\"","Think backwards?"),
   WOW("<b>Charlie's Inversion:</b> to keep a house of healing strong, imagine how it could FALL — care growing too expensive for ordinary families, or doctors growing careless and cold — then carefully avoid each one, keeping the doors open, the prices fair, and the hands kind."),
   P("ap_c9_verdict","Warren nodded. \"Trusted doctors, a wide network, and the scale to buy costly machines — a mighty castle, so long as its care stays affordable and kind.\"","I SEE the whole picture!"),
   NOTE("Charlotte's Secret Notebook · The Big Secret","Apollo is hard to copy: TRUSTED doctors, a wide NETWORK, and the SCALE to afford costly machines. But it must stay KIND and AFFORDABLE, or it loses the trust it stands on. Charlie's trick: picture how you'd lose (care too costly or too cold), then never do it. Invert! 🏰"),
 ]),
 ("c10","CHAPTER 10","The Marvel You Carry","pages 81-88",[
   P("ap_c10_wake","Charlotte woke in her own bed. The great hospital was gone… but she could feel her own heart beating softly, thump-thump.","Was it real? It FELT real…"),
   P("ap_c10_diary","On the diary's page, a new line glowed — as if Grandpa Ben wrote it just for her.",None,'"Now you know the marvel you carry, and the house that keeps it well. Well done."'),
   P("ap_c10_look","She ran outside at dusk. Every person passing by — young and old — carried a beating heart, breathing lungs, rivers of blood, quietly working away.","Everyone carries a marvel inside — I just couldn't see it!"),
   WOW("Next time you feel your heart beat, you'll know the secret: you carry a <b>wonderful machine</b> — a pump, a pair of bellows, and rivers that reach every corner. And when it needs help, a <b>house that heals</b> — trusted doctors, seeing machines, and a ready alarm — stands waiting. That's <b>the house that heals.</b> 🫀🏥"),
   NOTE("Charlotte's Secret Notebook · What I Learned","➊ The heart is a PUMP; the lungs are BELLOWS that catch air; the blood CARRIES it everywhere.<br>➋ They work as ONE system — a team.<br>➌ A hospital mirrors the body: scans that see inside, many specialists as one team, an emergency room like the body's alarm.<br>➍ Apollo Hospitals grew into a whole network of healing houses.<br>➎ Its moat is trusted doctors, a hard-to-copy network and scale — but Charlie's trick: picture how you'd lose (care too costly or cold), then keep it affordable and kind. 💛"),
 ]),
]

HOOK=("ap_c1_swirl","EVERY ORDINARY THING HIDES A SECRET.",
 "Charlotte found the marvel she carries inside — and the house built to heal it. But the compass is twitching again — toward the tiny pill that can chase away a fever overnight. Where does medicine come from, and how does one small tablet know exactly what to mend?",
 "NEXT ADVENTURE · The Tiny Healer →")

DIAGRAM='''<div class="panel wide" style="background:#fbf3ec;">
<svg viewBox="0 0 820 380"><rect width="820" height="380" fill="#fbf3ec"/>
<text x="410" y="38" text-anchor="middle" font-family="Bangers" font-size="24" fill="#e8425a">THE BODY WORKS AS ONE SYSTEM</text>
<g><circle cx="120" cy="150" r="34" fill="#8fd3ff" stroke="#1f9c8f" stroke-width="4"/><text x="120" y="112" text-anchor="middle" font-family="Baloo 2" font-size="15" fill="#1f9c8f">THE AIR</text><text x="120" y="235" text-anchor="middle" font-family="Nunito" font-size="13" fill="#555">you breathe it in</text></g>
<g stroke="#1f9c8f" stroke-width="5" fill="#1f9c8f"><line x1="160" y1="150" x2="300" y2="150" stroke-dasharray="10 8"/><path d="M296 141 L314 150 L296 159Z"/></g>
<g><rect x="320" y="112" width="150" height="90" rx="12" fill="#fff" stroke="#171717" stroke-width="4"/><text x="395" y="102" text-anchor="middle" font-family="Baloo 2" font-size="14" fill="#1f9c8f">THE LUNGS</text><text x="395" y="165" text-anchor="middle" font-family="Bangers" font-size="26" fill="#1f9c8f">catch it</text><text x="395" y="235" text-anchor="middle" font-family="Nunito" font-size="13" fill="#555">bellows fill with air</text></g>
<g stroke="#e8425a" stroke-width="5" fill="#e8425a"><line x1="480" y1="150" x2="600" y2="150" stroke-dasharray="10 8"/><path d="M596 141 L614 150 L596 159Z"/></g>
<text x="540" y="135" text-anchor="middle" font-family="Baloo 2" font-size="12" fill="#e8425a">the heart pumps</text>
<text x="540" y="182" text-anchor="middle" font-family="Nunito" font-size="12" fill="#555">once every second</text>
<g><rect x="620" y="112" width="150" height="90" rx="12" fill="#e8425a" stroke="#171717" stroke-width="4"/><text x="695" y="102" text-anchor="middle" font-family="Baloo 2" font-size="16" fill="#8a1f2c">THE BLOOD</text><text x="695" y="165" text-anchor="middle" font-family="Bangers" font-size="24" fill="#fff">carries it</text><text x="695" y="235" text-anchor="middle" font-family="Nunito" font-size="13" fill="#555">rivers to every corner</text></g>
<rect x="70" y="300" width="680" height="52" rx="9" fill="#fff" stroke="#171717" stroke-width="3"/>
<text x="410" y="322" text-anchor="middle" font-family="Nunito" font-size="14" fill="#123">Lungs catch the air &#8594; the heart PUMPS the blood &#8594; the blood CARRIES air and food to every part of you.</text>
<text x="410" y="343" text-anchor="middle" font-family="Nunito" font-size="13" fill="#555">A hospital mirrors the body: many specialists, working together as one system.</text>
</svg><div class="figcap">The lungs catch the air, the heart pumps the blood, and the blood carries it everywhere — and a hospital works the very same way.</div></div>'''

try:
    from book_extra import EXTRA, NEW2
    NEW.update(NEW2)
except Exception:
    EXTRA={}

def render_panel(pn,pageno=None):
    _,img,cap,b1,b2,sfx,sfxc,tall=pn
    pg=f'<div class="pageno">{pageno}</div>' if pageno else ''
    p=[f'<div class="panel wide">{pg}<img src="art/{img}.jpg" alt="" loading="lazy">']
    if cap: p.append(f'<div class="cap tl tilt">{cap}</div>')
    if b1: p.append(f'<div class="bubble dl" style="left:12px;bottom:12px;">{b1}</div>')
    if b2: p.append(f'<div class="bubble dr" style="right:12px;top:12px;">{b2}</div>')
    if sfx: p.append(f'<div class="sfx" style="left:40%;top:14px;font-size:32px;color:{sfxc};">{sfx}</div>')
    p.append('</div>'); return "".join(p)

def render_item(it,pageno=None):
    t=it[0]
    if t=="panel": return render_panel(it,pageno)
    if t=="diagram": return DIAGRAM
    if t=="sub": return f'<div class="sub"><span class="dot">{it[1]}</span><b>{it[2]}</b></div>'
    if t=="wow": return f'<div class="wow">{it[1]}</div>'
    if t=="note": return f'<div class="note"><div class="nt">{it[1]}</div><p>{it[2]}</p></div>'
    if t=="timeline":
        rows="".join(f'<div class="tl"><div class="yr">{y}</div><p>{x}</p></div>' for y,x in it[1])
        return f'<div class="timeline">{rows}</div>'
    if t=="moat":
        cards="".join(f'<div class="mc{" bad" if bad else ""}"><h4>{ic} {ti}</h4><p>{tx}</p></div>' for ic,ti,tx,bad in it[1])
        return f'<div class="moat">{cards}</div>'
    return ""

def referenced_images():
    imgs=set()
    for cls,_,_,_,items in CHAPTERS:
        for it in items:
            if it[0]=="panel": imgs.add(it[1])
        for it in EXTRA.get(cls,[]):
            if it[0]=="panel": imgs.add(it[1])
    imgs.add(HOOK[0]); imgs.add("00_cover"); imgs.add("_ref_iris"); return imgs

def build():
    body=[]; pageno=0
    for cls,num,title,pglabel,items in CHAPTERS:
        items=list(items); extra=EXTRA.get(cls,[])
        if extra:
            idx=[i for i,it in enumerate(items) if it[0]=="panel"]
            at=(idx[-1]+1) if idx else len(items)
            for ex in reversed(extra): items.insert(at,ex)
        start=pageno+1
        inner=[f'<div class="chapbar {cls}"><div class="n">{num}</div><h2>{title}</h2></div>']
        for it in items:
            if it[0]=="panel": pageno+=1; inner.append(render_item(it,pageno))
            else: inner.append(render_item(it))
        lbl=f"pages {start}-{pageno}" if pageno>=start else pglabel
        body.append(f'<div class="sheet" data-pg="{lbl}">{"".join(inner)}</div>')
    hook=f'''<div class="sheet" data-pg="the end… for now"><div class="hook"><img src="art/{HOOK[0]}.jpg" alt="">
<div class="hc"><h3>{HOOK[1]}</h3><p>{HOOK[2]}</p><div class="b2">{HOOK[3]}</div></div></div></div>'''
    head=open("/root/omahaindia.com/comics/site/book/apollo/_head.html").read()
    tail=open("/root/omahaindia.com/comics/site/book/apollo/_tail.html").read()
    open(OUT,"w").write(head+"".join(body)+hook+tail)
    print("built",OUT,"| chapters:",len(CHAPTERS),"| images:",len(referenced_images()))

if __name__=="__main__":
    build()
