#!/usr/bin/env python3
# Book 39 (Dr. Reddy's Laboratories) — THE CLEVER COPYCAT CURE. Science->business: a medicine is a
# tiny KEY (a molecule) whose SHAPE fits a LOCK in the body -> the inventor gets years alone with the key
# (a patent) -> then the recipe goes public and clever chemists copy the exact same shape for far less
# (generics) -> copy it wrong by one atom and the key won't turn, so precision is everything -> the giant
# of careful copycat cures that heals the world cheaply.
import os
ART="/root/omahaindia.com/comics/site/book/drreddy/art"
OUT="/root/omahaindia.com/comics/site/book/drreddy/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"
ALMA=("Alma, a warm friendly Western CHEMIST, NOT Indian, silver-streaked bob haircut, sharp curious smile, "
"a crisp white lab coat, purple rubber gloves, holding a glass flask of clear liquid")

# name -> (w,h,seed,prompt,ref). ref set -> Seedream character; None -> flux scene. Ritual panels copied by mkbook.
NEW={
 "00_cover":(1024,1180,3900,f"{STYLE}. BOOK COVER, {CHARLOTTE} standing with {ALMA} in a gleaming medicine laboratory, holding up a glowing molecule shaped like a tiny golden key that fits a floating keyhole of light, rows of bright glass flasks and a hopeful glow, wonder, cinematic","charlotte"),
 "_ref_alma":(1024,1024,3901,f"{STYLE}. clean friendly character portrait, {ALMA}, plain soft warm background, kind smile, head and shoulders",None),
 # Ch1
 "dr_c1_coin":(1024,720,3910,f"{STYLE}. {CHARLOTTE} at home, Grandpa Ben's glowing brass compass twitching between a tiny white pill and a little brass keyhole glowing on the table, EXPRESSION puzzled and intrigued, cozy lamp light","charlotte"),
 "dr_c1_diary":(1024,720,3911,f"{STYLE}. an open magical diary glowing warm gold on a desk, a faint ribbon of golden light rising from the page and curling into the shape of a tiny key, no people",None),
 "dr_c1_swirl":(1024,720,3912,f"{STYLE}. {CHARLOTTE} pulled into a swirling spiral of golden light and floating tiny keys from a glowing diary, EXPRESSION thrilled, magical","charlotte"),
 # Ch2 — arrive at the laboratory, meet Alma
 "dr_c2_arrive":(1024,720,3913,f"{STYLE}. {CHARLOTTE} landing wide-eyed in the brightest room she has ever seen, rows of glass flasks, bubbling tubes and shining silver machines, EXPRESSION awe and delight, bright clean light","charlotte"),
 "dr_c2_alma":(1024,720,3914,f"{STYLE}. {ALMA} warmly welcoming {CHARLOTTE} in the laboratory, holding up her flask, EXPRESSION Charlotte shy happy smile; keep the SAME chemist from the reference, same white lab coat, same purple gloves, same silver-streaked bob","alma"),
 "dr_c2_lab":(1024,720,3915,f"{STYLE}. a vast gleaming pharmaceutical laboratory hall, giant polished steel vats and endless rows of glassware winding away, tiny workers in white coats for scale, powerful and awe-inspiring, no faces close up",None),
 # Ch3 — the locks inside us: a medicine is a key whose shape fits
 "dr_c3_lock":(1024,720,3916,f"{STYLE}. {ALMA} kneeling to show {CHARLOTTE} a tiny glowing model of a keyhole, a warm spark of light inside it waiting, EXPRESSION Charlotte fascinated leaning in; SAME chemist, white lab coat, purple gloves","alma"),
 "dr_c3_body":(1024,720,3917,f"{STYLE}. a whimsical magical view inside the human body, countless tiny glowing keyholes dotted across the walls of cells like little doors, warm and alive, gentle glow, no people",None),
 "dr_c3_key":(1024,720,3918,f"{STYLE}. a friendly close up of a single glowing golden molecule shaped like a tiny key sliding into a matching keyhole of light and turning it, playful science, no people",None),
 # Ch4 — the inventor's years alone with the key (the patent)
 "dr_c4_invent":(1024,720,3919,f"{STYLE}. {CHARLOTTE} watching in wonder as a lone chemist, seen at a gentle distance, works season after season at a glowing desk of notes and flasks, slowly shaping a single tiny golden key, EXPRESSION Charlotte curious and absorbed, warm lamplight","charlotte"),
 "dr_c4_patent":(1024,720,3920,f"{STYLE}. a magical scene of a single glowing golden key sealed under a shining glass dome behind a padlock, a big friendly clock beside it slowly ticking the years, warm underground glow, no people",None),
 "dr_c4_vault":(1024,720,3921,f"{STYLE}. a beautiful close up of one precious golden molecule-key glowing alone in a spotlight behind glass, one of a kind and carefully guarded, dark rim bright center, no people",None),
 # Ch5 — the recipe goes public, generics copy the exact shape for far less
 "dr_c5_public":(1024,720,3922,f"{STYLE}. an open glowing recipe book on a bright table, a shining diagram of a key-shaped molecule rising off the page for all to read, its secret now shared, warm golden light, no people",None),
 "dr_c5_copy":(1024,720,3923,f"{STYLE}. {ALMA} showing {CHARLOTTE} how many identical copies of the very same golden key are being made side by side on a bench, EXPRESSION Charlotte gleeful realization; SAME chemist, white lab coat, purple gloves","alma"),
 # Ch6 — precision: one atom wrong and the key won't turn
 "dr_c6_atom":(1024,720,3924,f"{STYLE}. {CHARLOTTE} peering closely at two nearly identical golden keys held side by side, one whisker different from the other, EXPRESSION concentrating hard and squinting, bright hall","charlotte"),
 "dr_c6_fit":(1024,720,3925,f"{STYLE}. a perfect golden key turning smoothly in a matching lock with a happy burst of warm light, while a slightly-wrong key nearby stays stuck, magical, no people",None),
 # Ch7 — cheap cures for everyone
 "dr_c7_everyone":(1024,720,3926,f"{STYLE}. a joyful scene of affordable medicine reaching everyone — a bright pharmacy, a village clinic, a hospital ward — all warm and hopeful, no faces close up",None),
 "dr_c7_world":(1024,720,3927,f"{STYLE}. a warm storybook world map with little glowing medicine bottles travelling from one bright laboratory out to countries across the whole globe, gentle and grand, no people",None),
 # Ch8 — reveal Dr. Reddy's Laboratories
 "dr_c8_reveal":(1024,720,3928,f"{STYLE}. {CHARLOTTE} and {ALMA} standing proudly at a window over a vast spotless medicine factory glowing against a blue sky, EXPRESSION proud recognition; SAME chemist, white lab coat, purple gloves","charlotte"),
 "dr_c8_1984":(1024,720,3929,f"{STYLE}. warm sepia 1980s scene, a small hopeful laboratory in Hyderabad with a few flasks and eager workers in white coats beginning to copy great medicines, inspiring, no text",None),
 "dr_c8_scale":(1024,720,3930,f"{STYLE}. a mighty modern pharmaceutical plant at golden hour, gleaming steel towers and long packing lines shipping cures by the millions, one of India's biggest medicine-makers, proud and grand, no people",None),
 # Ch10 (ch9 uses ritual castle/invert/verdict; ch10 uses ritual wake/diary)
 "dr_c10_look":(1024,720,3931,f"{STYLE}. {CHARLOTTE} peeking into a home medicine cabinet, every little pill and bottle glowing softly, knowing each one holds a tiny key copied with enormous care, 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 Tiny Key That Heals","pages 1-8",[
   P("dr_c1_coin","Back home, Grandpa Ben's compass twitched again — pointing between a tiny white pill and a little brass keyhole glowing on the table.","A pill… and a keyhole? What's the link?",None,"twitch"),
   P("dr_c1_diary","The old diary fell open. A new line shimmered in Grandpa Ben's hand.",None,'"Find the tiny key that turns a lock hidden inside us."'),
   WOW("A little pill and a lock don't seem to belong together — yet swallow the right one and an aching, ailing body can be mended good as new. What secret is hiding inside a medicine? That's the puzzle of this whole adventure."),
   P("dr_c1_swirl","Golden light swirled up and pulled Charlotte in.","Here we GO!",None,"WHOOSH","#c8621f"),
   NOTE("Charlotte's Secret Notebook","Two BIG questions:<br>➊ How can one tiny pill mend a whole body?<br>➋ Grandpa Ben says a medicine is a <i>key</i>. A key to <i>what</i> lock? 🔑"),
 ]),
 ("c2","CHAPTER 2","The Gleaming Laboratory","pages 9-16",[
   P("dr_c2_arrive","One blink, and she stood in the brightest room she'd ever seen — rows of glass flasks, bubbling tubes and shining silver machines.","It's a whole palace made of GLASS!"),
   P("dr_c2_alma","A woman in a white coat and purple gloves smiled. \"I'm Alma, a chemist. In here we build tiny keys that heal people.\"","Keys… that HEAL?!"),
   P("dr_c2_lab","Down the hall, giant gleaming vats and glassware stretched further than she could see.","So much shiny science — all to make medicine?","Stick with me, kiddo."),
   NOTE("Charlotte's Secret Notebook","Alma is a chemist (a scientist of what things are made of), and she grins like she has a secret — just like the other guides did. She calls medicines 'tiny keys'. Okay Alma… show me how! ✨"),
 ]),
 ("c3","CHAPTER 3","The Locks Inside Us","pages 17-26",[
   P("dr_c3_lock","Alma held up a tiny model of a keyhole. \"Your body is full of little locks. When one gets stuck, you feel poorly.\"","My body has LOCKS in it?"),
   P("dr_c3_body","\"Millions of them,\" she said, \"in every cell — each a tiny keyhole waiting for exactly the right shape.\"","A whole world of tiny locks!"),
   P("dr_c3_key","\"A medicine is a molecule — a tiny KEY. It only works if its shape fits the lock and turns it.\"","So a cure is a key that FITS!",None,"click","#c8621f"),
   WOW("Here's the first secret! 🔑 A medicine is a <b>molecule</b> — a tiny shape, like a <b>key</b>. Your body is full of tiny <b>locks</b>. A medicine helps only when its shape fits a lock exactly and <b>turns it</b>. Wrong shape, and nothing happens."),
   ("diagram",),
   NOTE("Charlotte's Secret Notebook","My body is full of tiny locks. A medicine is a molecule shaped like a KEY. It only heals if its shape fits the lock and turns it. Shape is everything! 🔑🧬"),
 ]),
 ("c4","CHAPTER 4","The Inventor's Secret Key","pages 27-36",[
   P("dr_c4_invent","\"Finding a brand-new key is VERY hard,\" said Alma. \"A clever chemist might search for years to shape the very first one.\"","Years — just for one tiny key?"),
   P("dr_c4_patent","\"So the world makes a promise: whoever invents a new key may be the ONLY one to make it for some years. That promise is a patent.\"","A key that's the inventor's alone!",None,"sealed","#37414d"),
   P("dr_c4_vault","\"For those years the inventor is alone with the key,\" she said, \"and can charge a lot, because no one else may make it.\"","Locked away — but only for a while!"),
   WOW("Inventing a brand-new medicine takes <b>years</b> of careful work. As a reward, the inventor earns a <b>patent</b> — for a set number of years, they alone may make that key. During that time the medicine can be <b>costly</b>, because there is no one else to make it."),
   NOTE("Charlotte's Secret Notebook · SOLVED (part 1)","A brand-new medicine is a key that took years to shape. The inventor earns a PATENT — for some years, only they may make it, so it costs a lot. 🔒⏳"),
 ]),
 ("c5","CHAPTER 5","When the Recipe Goes Public","pages 37-44",[
   P("dr_c5_public","\"But a patent doesn't last forever,\" Alma smiled. \"When it ends, the recipe becomes public — for ALL to read.\"","The secret recipe — shared with everyone?",None,"ta-da","#c8621f"),
   P("dr_c5_copy","\"Then clever chemists like us copy the very same key — the exact same shape — and make it for far, FAR less.\"","Same cure… but cheap for everyone!"),
   WOW("A patent ends once its years are up, and the recipe becomes <b>public</b>. Now clever chemists can make a <b>copy</b> of the exact same molecule — a <b>generic</b>. It's the very same key, so it heals just the same, but it costs a tiny fraction of the price."),
   NOTE("Charlotte's Secret Notebook","When a patent ends, the recipe is public. Clever chemists copy the EXACT same key — a 'generic' — for much less money. Same cure, tiny price! 💊"),
 ]),
 ("c6","CHAPTER 6","One Atom Wrong","pages 45-52",[
   P("dr_c6_atom","\"But copying is tricky,\" Alma warned, holding up two keys almost alike. \"Get one tiny atom wrong, and the shape changes.\"","They look the same to me…"),
   P("dr_c6_fit","\"A key that's off by a whisker won't turn the lock — or worse. So we must copy it PERFECTLY, every single time.\"","So being exact is the WHOLE job!",None,"click!","#c8621f"),
   WOW("Copying sounds easy — it isn't. A molecule is a precise shape, and <b>one wrong atom</b> makes a different key that <b>won't turn the lock</b> (and could even harm). A great generic-maker must copy the shape <b>perfectly, every time.</b> Precision is everything."),
   NOTE("Charlotte's Secret Notebook · SOLVED!","A copy must be PERFECT. One atom out of place and the key won't fit the lock. Making the exact same shape, every single time, is the hardest and most important part. 🎯"),
 ]),
 ("c7","CHAPTER 7","Cheap Cures for Everyone","pages 53-60",[
   P("dr_c7_everyone","Alma swept her arm wide — a bright pharmacy, a village clinic, a hospital ward, all reaching for the same little pills.","Everyone can afford the cure now?!"),
   P("dr_c7_world","\"When a good key is copied well and cheaply,\" she said, \"medicine reaches MILLIONS who could never pay the first high price.\"","The same cure — for the whole world!"),
   WOW("This isn't a small thing. Affordable <b>generic medicines</b> let millions of people — in villages, clinics and hospitals everywhere — get cures that were once far too dear. A perfect, cheap copy of the right key can quietly save an enormous number of lives."),
   NOTE("Charlotte's Secret Notebook","When a cure is copied perfectly AND cheaply, it reaches millions who could never afford the first costly version. Cheap, exact copies save lives all over the world. 🌏💛"),
 ]),
 ("c8","CHAPTER 8 · THE BIG DISCOVERY","The Copycat Chemists of Hyderabad","pages 61-70",[
   P("dr_c8_reveal","Alma led Charlotte to a window over a vast, spotless medicine factory humming below.","Who makes ALL these cheap cures?"),
   P("dr_c8_1984","\"In 1984, in Hyderabad,\" said Alma, \"a determined chemist started a company to copy great medicines and sell them for less.\"","One small lab, with a big dream!"),
   P("dr_c8_scale","\"It grew and grew — into one of India's biggest medicine-makers, sending copied cures all over the world.\"","From one lab to the whole PLANET!"),
   WOW("A \"company\" can be a giant shared job. <b>Dr. Reddy's Laboratories</b> began in 1984 in Hyderabad, making clever, careful copies of medicines. It grew into one of India's largest drug-makers, shipping affordable cures to dozens of countries."),
   TL([("1984","A determined chemist starts a small lab in Hyderabad to copy great medicines for less."),
       ("Over decades","It grows into one of India's biggest medicine-makers."),
       ("Today","Its careful copied cures reach patients in dozens of countries."),
       ("Tomorrow","It works to invent brand-new keys of its own, not only copy them. 🔬")]),
   NOTE("Charlotte's Secret Notebook","Dr. Reddy's Laboratories (1984, Hyderabad) grew from one small lab into a giant that copies great medicines PERFECTLY and cheaply, sending cures around the world. 🏆"),
 ]),
 ("c9","CHAPTER 9","The Castle of Careful Chemists","pages 71-80",[
   P("dr_c9_castle","Two kind old men appeared with a glow. Warren pointed at a castle standing over the gleaming laboratories. \"What keeps rivals out, Charlotte?\"","Walls! But what kind?"),
   MOAT([("🧪","Wall One: Hard, Careful Chemistry","Copying a key PERFECTLY, atom for atom, is fiendishly hard. Only a few chemists in the world are skilled enough to do it right, every single time.",False),
         ("🏭","Wall Two: Factories the Inspectors Trust","The strictest inspectors on Earth check these factories for the tiniest speck of a mistake. Passing again and again takes years to earn — and rivals can't fake it.",False),
         ("🌏","Wall Three: Trusted All Over the World","Doctors and whole countries far away rely on these copied cures. Being trusted with people's health is very hard to win and easy to lose.",False),
         ("⚠️","The Crack in the Wall","Once a recipe is public, MANY copycats can make the same key. When lots of them crowd in, the price falls fast — so a copy is only richly rewarding for a little while.",True)]),
   P("dr_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 medicine-maker strong, imagine how it could FADE — a sloppy factory that fails inspection, or racing so many copycats that prices collapse — then carefully avoid each one, and keep inventing fresh keys others can't copy yet."),
   P("dr_c9_verdict","Warren nodded. \"Careful chemistry and trusted factories are a real castle — so long as it keeps finding new keys before the copycats crowd in.\"","I SEE the whole picture!"),
   NOTE("Charlotte's Secret Notebook · The Big Secret","Dr. Reddy's is hard to copy: PERFECT chemistry, factories the world's strictest inspectors trust, and cures doctors rely on. But once a recipe is public, MANY copy it and prices fall fast. Charlie's trick: picture how you'd lose (a failed factory, a price war), then never do it. Invert! 🏰"),
 ]),
 ("c10","CHAPTER 10","The Key in Your Medicine Cabinet","pages 81-88",[
   P("dr_c10_wake","Charlotte woke in her own bed. The gleaming lab was gone… but the tiny white pill on her desk shimmered softly.","Was it real? It FELT real…"),
   P("dr_c10_diary","On the diary's page, a new line glowed — as if Grandpa Ben wrote it just for her.",None,'"Now you see the tiny key that turns a lock inside us. Well done."'),
   P("dr_c10_look","She peeked in the medicine cabinet — every little pill and bottle, she now knew, was a tiny key, copied with enormous care.","They were tiny keys the whole time — I just couldn't see it!"),
   WOW("Next time you see a medicine, you'll know the secret: it's a <b>tiny key</b>, a molecule shaped to fit a lock in your body. Inventors earn years alone with a new key; then clever chemists copy the exact shape for far less — as long as they get every atom <b>perfectly</b> right. That's <b>the clever copycat cure.</b> 🔑💊"),
   NOTE("Charlotte's Secret Notebook · What I Learned","➊ A medicine is a molecule — a tiny KEY shaped to fit a lock in the body.<br>➋ Inventing a new key is hard, so the inventor earns a PATENT — years to make it alone.<br>➌ When the patent ends, chemists copy the exact same key cheaply — a generic.<br>➍ One atom wrong and the key won't turn, so precision is everything.<br>➎ Dr. Reddy's copies keys perfectly in trusted factories; but Charlie's trick — picture how you'd lose (a failed factory, a price war), then keep finding new keys. 💛"),
 ]),
]

HOOK=("dr_c1_swirl","EVERY ORDINARY THING HIDES A SECRET.",
 "Charlotte found the tiny key hidden inside a medicine. But the compass is twitching again — this time toward the little glowing screen in everyone's pocket, buzzing with words that leap invisibly across the whole world. How do our voices fly so far?",
 "NEXT ADVENTURE · Voices on Invisible Threads →")

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="#c8621f">A MEDICINE IS A TINY KEY</text>
<g><circle cx="120" cy="150" r="34" fill="#f6b53f" stroke="#c8621f" stroke-width="4"/><text x="120" y="112" text-anchor="middle" font-family="Baloo 2" font-size="15" fill="#c8621f">THE KEY</text><text x="120" y="235" text-anchor="middle" font-family="Nunito" font-size="13" fill="#555">a medicine molecule</text></g>
<g stroke="#2aa15a" stroke-width="5" fill="#2aa15a"><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="#2aa15a">A LOCK IN YOU</text><text x="395" y="165" text-anchor="middle" font-family="Bangers" font-size="26" fill="#2aa15a">it fits</text><text x="395" y="235" text-anchor="middle" font-family="Nunito" font-size="13" fill="#555">a keyhole in every cell</text></g>
<g stroke="#37414d" stroke-width="5" fill="#37414d"><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="#37414d">turn the key</text>
<text x="540" y="182" text-anchor="middle" font-family="Nunito" font-size="12" fill="#555">the lock opens</text>
<g><rect x="620" y="112" width="150" height="90" rx="12" fill="#37414d" stroke="#171717" stroke-width="4"/><text x="695" y="102" text-anchor="middle" font-family="Baloo 2" font-size="16" fill="#c8621f">A CURE</text><text x="695" y="165" text-anchor="middle" font-family="Bangers" font-size="24" fill="#f6b53f">you heal!</text><text x="695" y="235" text-anchor="middle" font-family="Nunito" font-size="13" fill="#555">the body is mended</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">A patent gives the inventor years alone with a new key &#8594; then chemists copy the EXACT shape for far less (a generic).</text>
<text x="410" y="343" text-anchor="middle" font-family="Nunito" font-size="13" fill="#555">Get one atom wrong and the key won't turn &#8212; so copying it perfectly is everything.</text>
</svg><div class="figcap">A medicine is a molecule shaped like a key; it fits a lock in the body and turns it to heal. Copy the exact shape and the cure gets cheap.</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_alma"); 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/drreddy/_head.html").read()
    tail=open("/root/omahaindia.com/comics/site/book/drreddy/_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()
