#!/usr/bin/env python3
# Book 25 (Hindalco Industries) — THE METAL THAT FLIES. Science->business: aluminium is hidden in RED
# EARTH (bauxite) -> freed by pushing a LOT of electricity through it (electrolysis) -> a light metal that
# never rusts and can be melted and reborn forever -> the giant that owns the earth, the power and the scale.
import os
ART="/root/omahaindia.com/comics/site/book/hindalco/art"
OUT="/root/omahaindia.com/comics/site/book/hindalco/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"
OTTO=("Otto, a warm friendly Western METALLURGIST, NOT Indian, stocky build, cheerful bearded face, "
"a silver heat-proof jacket, safety goggles pushed up on his forehead, a pair of long tongs in one hand")

# name -> (w,h,seed,prompt,ref). ref set -> Seedream character; None -> flux scene. Ritual panels copied by mkbook.
NEW={
 "00_cover":(1024,1180,2500,f"{STYLE}. BOOK COVER, {CHARLOTTE} standing with {OTTO} on a bluff of glowing red earth, holding up a feather-light silvery ingot that catches the sun, a shining aeroplane climbing into a bright sky above them, wonder, cinematic","charlotte"),
 "_ref_otto":(1024,1024,2501,f"{STYLE}. clean friendly character portrait, {OTTO}, plain soft warm background, cheerful smile, head and shoulders",None),
 # Ch1
 "hi_c1_coin":(1024,720,2510,f"{STYLE}. {CHARLOTTE} at home, Grandpa Ben's glowing brass compass twitching between a crumb of red earth and a shiny silver drink can on the table, EXPRESSION puzzled and intrigued, cozy lamp light","charlotte"),
 "hi_c1_diary":(1024,720,2511,f"{STYLE}. an open magical diary glowing warm gold on a desk, a faint ribbon of silver light rising from the page and curling around a small clod of red earth, no people",None),
 "hi_c1_swirl":(1024,720,2512,f"{STYLE}. {CHARLOTTE} pulled into a swirling spiral of golden light and red-and-silver dust from a glowing diary, EXPRESSION thrilled, magical","charlotte"),
 # Ch2 — arrive at the red earth, meet Otto
 "hi_c2_arrive":(1024,720,2513,f"{STYLE}. {CHARLOTTE} landing wide-eyed on a wide plateau of astonishing rust-red earth stretching to the horizon, red dust puffing round her shoes, EXPRESSION startled delight, bright daylight","charlotte"),
 "hi_c2_otto":(1024,720,2514,f"{STYLE}. {OTTO} warmly welcoming {CHARLOTTE} on the red plateau, raising his tongs in a cheerful hello, EXPRESSION Charlotte shy happy smile; keep the SAME metallurgist from the reference, same silver heat-proof jacket, same goggles on his forehead, same tongs","otto"),
 "hi_c2_pit":(1024,720,2515,f"{STYLE}. a wide red bauxite mine seen from above, broad shelves of rust-red rock, tiny yellow trucks crawling along the ledges for scale, red dust in the warm air, no faces close up",None),
 # Ch3 — the metal hiding in the red earth
 "hi_c3_scoop":(1024,720,2516,f"{STYLE}. {OTTO} kneeling to pour a handful of crumbly red earth into {CHARLOTTE}'s cupped palms, tiny silver sparks winking hidden among the red crumbs, EXPRESSION Charlotte fascinated leaning in; SAME metallurgist, silver jacket, goggles on forehead, tongs","otto"),
 "hi_c3_hidden":(1024,720,2517,f"{STYLE}. a magical close up of a crumb of red bauxite cut open, thousands of tiny silvery specks glowing softly inside like stars trapped in clay, playful science, no people",None),
 "hi_c3_locked":(1024,720,2518,f"{STYLE}. a friendly picture of a little silver droplet held tight inside a red crystal cage, gently straining to get out, playful storybook science, no people",None),
 # Ch4 — electricity is the key that frees it
 "hi_c4_key":(1024,720,2519,f"{STYLE}. {CHARLOTTE} watching in wonder as a crackling blue bolt of electricity acts like a glowing key turning in the lock of a red crystal cage, EXPRESSION amazed and thoughtful, dramatic sparks","charlotte"),
 "hi_c4_pots":(1024,720,2520,f"{STYLE}. a colossal hall of glowing electrolysis pots stretching away into the distance, thick copper busbars overhead, molten silver metal shimmering under a bright crust, warm and awe-inspiring, no people",None),
 "hi_c4_hungry":(1024,720,2521,f"{STYLE}. a magical picture of a river of blue electricity pouring into a glowing pot of red earth, a bright silver puddle forming at the bottom, huge power lines feeding in from a distant power station, no people",None),
 # Ch5 — the metal is LIGHT
 "hi_c5_light":(1024,720,2522,f"{STYLE}. {OTTO} handing {CHARLOTTE} a big silvery block that turns out to weigh almost nothing, her arms flying up in surprise at how light it is, EXPRESSION Charlotte astonished laughing 'oh!'; SAME metallurgist, silver jacket, goggles on forehead, tongs","otto"),
 "hi_c5_fly":(1024,720,2523,f"{STYLE}. a beautiful silver aeroplane climbing steeply into a bright blue sky, sunlight running along its light metal skin, hopeful and grand, no people",None),
 # Ch6 — it does not rust
 "hi_c6_rain":(1024,720,2524,f"{STYLE}. {CHARLOTTE} holding a shiny silver sheet out into the falling rain while an old iron bar beside it drips with orange rust, EXPRESSION triumphant and pleased, soft rainy light","charlotte"),
 "hi_c6_shield":(1024,720,2525,f"{STYLE}. a magical close up of a silvery metal surface growing its own invisible glassy shield against the weather, raindrops beading and rolling away harmlessly, playful science, no people",None),
 # Ch7 — melted and reborn forever
 "hi_c7_melt":(1024,720,2526,f"{STYLE}. a crumpled silver can dropping into a glowing crucible and melting into a bright liquid pool, then flowing out as a clean shining new ingot, a circle of rebirth, warm foundry light, no people",None),
 "hi_c7_forever":(1024,720,2527,f"{STYLE}. a joyful storybook loop showing a can becoming molten metal becoming a fresh new can again and again, tiny sparkles of saved energy floating around the circle, cheerful, no people",None),
 # Ch8 — reveal Hindalco
 "hi_c8_reveal":(1024,720,2528,f"{STYLE}. {CHARLOTTE} and {OTTO} standing proudly before a vast aluminium smelter with its own power station and red mine behind it, glowing against a blue sky, EXPRESSION proud recognition; SAME metallurgist, silver jacket, goggles on forehead, tongs","charlotte"),
 "hi_c8_1958":(1024,720,2529,f"{STYLE}. warm sepia late-1950s scene, the very first aluminium works rising on an empty plain, hopeful engineers and old machines, the beginning of something big, inspiring, no text",None),
 "hi_c8_scale":(1024,720,2530,f"{STYLE}. a mighty modern aluminium works at golden hour, red mine on one side, power station chimneys in the middle, silver ingots stacked in gleaming rows, proud and grand, no people",None),
 # Ch10 (ch9 uses ritual castle/invert/verdict; ch10 uses ritual wake/diary)
 "hi_c10_look":(1024,720,2531,f"{STYLE}. {CHARLOTTE} outside at dusk gazing up as a plane's lights cross the sky, a silver can and a window frame gleaming softly nearby, knowing each one began as red earth, 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 Red Earth and the Shiny Can","pages 1-8",[
   P("hi_c1_coin","Back home, Grandpa Ben's compass twitched again — pointing between a crumb of red dirt and a bright silver can.","Red mud… and a shiny can? They're nothing alike!",None,"twitch"),
   P("hi_c1_diary","The old diary fell open. A new line shimmered in Grandpa Ben's hand.",None,'"Find the metal that is sleeping inside the red earth."'),
   WOW("A handful of red dirt and a gleaming silver can look like opposites. Yet one of them is <i>made</i> of the other. How do you pull a shiny metal out of plain mud — and why does that metal let aeroplanes fly? That's the puzzle of this whole adventure."),
   P("hi_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 a shiny metal be hiding inside plain red mud?<br>➋ Grandpa Ben says it's <i>sleeping</i> in there. What on earth would wake it up? ✨"),
 ]),
 ("c2","CHAPTER 2","The Plateau That Was Rust-Red","pages 9-16",[
   P("hi_c2_arrive","One blink, and she stood on a wide plain the colour of rust, red dust puffing round her shoes.","The whole GROUND is red!"),
   P("hi_c2_otto","A cheerful bearded man in a silver jacket waved his tongs. \"I'm Otto, a metal scientist. This red earth is full of treasure.\"","Treasure? In the DIRT?!"),
   P("hi_c2_pit","Far below, tiny trucks crawled along wide red shelves of rock, carrying the earth away by the tonne.","They're mining… mud?","Stick with me, kiddo."),
   NOTE("Charlotte's Secret Notebook","Otto is a metal scientist (a metallurgist), and he grins like he has a secret — just like the other guides did. He calls this red earth 'treasure'. Okay Otto… prove it! ✨"),
 ]),
 ("c3","CHAPTER 3","The Metal That Was Hiding","pages 17-26",[
   P("hi_c3_scoop","Otto poured red crumbs into her palms. Held to the light, tiny silver specks winked back at her.","There's something SHINY in here!"),
   P("hi_c3_hidden","\"This red earth is called bauxite,\" he said. \"Packed inside it is a metal — aluminium. Loads of it.\"","The metal's been in the mud all along!"),
   P("hi_c3_locked","\"But it won't just fall out. Each speck is locked up tight, glued to the earth around it.\"","Locked in! So how do you get it OUT?",None,"click","#c8621f"),
   WOW("Here's the first secret! 🔎 The shiny metal <b>aluminium</b> doesn't sit around in lumps waiting to be picked up. It hides <b>inside red earth called bauxite</b>, locked tight to the rock. It's one of the most common things under our feet — and one of the hardest to set free."),
   ("diagram",),
   NOTE("Charlotte's Secret Notebook","The red earth is called BAUXITE. Aluminium is hiding inside it — lots of it — but it's locked to the rock and won't come out on its own. Need a key! 🔑"),
 ]),
 ("c4","CHAPTER 4","The Key Made of Lightning","pages 27-36",[
   P("hi_c4_key","\"There's only one key that fits,\" said Otto, and a blue bolt crackled to life. \"Electricity.\"","Lightning is the KEY?!"),
   P("hi_c4_pots","\"We melt the earth in giant pots and push electricity straight through it. The grip lets go — and the metal drips out, pure and silver.\"","Electricity is pulling it loose!",None,"BZZZT","#2f6fd0"),
   P("hi_c4_hungry","\"And it drinks power,\" Otto warned. \"A smelter needs so much electricity that it wants a power station of its very own.\"","It's a HUNGRY kind of magic…"),
   WOW("Pushing electricity through the melted earth to split the metal free is called <b>electrolysis</b>. It works beautifully — but it is <b>enormously hungry</b>. Making aluminium takes so much electricity that smelters are built beside their own power stations. Remember that hunger; it matters later."),
   NOTE("Charlotte's Secret Notebook · SOLVED (part 1)","ELECTROLYSIS: push electricity through the melted red earth and the metal lets go — silver aluminium drips out. But it eats a MOUNTAIN of electricity. ⚡"),
 ]),
 ("c5","CHAPTER 5","Lighter Than It Looks","pages 37-44",[
   P("hi_c5_light","Otto passed her a block the size of a brick. Charlotte braced… and nearly flung it over her head.","It weighs almost NOTHING!",None,"whoop","#2aa15a"),
   P("hi_c5_fly","\"That,\" said Otto, watching a plane climb, \"is why they fly. A heavy metal would never leave the ground.\"","Light metal… so it can FLY!"),
   WOW("Aluminium is a metal that is <b>astonishingly light</b> — a block of it weighs about a third of the same block of steel. That lightness is everything: it lets <b>aeroplanes lift off</b>, trains run leaner, and cans stack high without crushing each other. Strong enough to hold, light enough to fly."),
   NOTE("Charlotte's Secret Notebook","Aluminium is SUPER light — about a third the weight of steel. That's why planes are made of it. A heavy plane would never get off the ground! ✈️"),
 ]),
 ("c6","CHAPTER 6","The Metal That Never Rusts","pages 45-52",[
   P("hi_c6_rain","Charlotte held a silver sheet out in the rain. Beside it, an old iron bar wept orange rust.","The iron's going crumbly — but this one's still SHINY!"),
   P("hi_c6_shield","\"It makes its own invisible shield,\" Otto explained. \"Wind, rain, years — it just shrugs them off.\"","It protects ITSELF?!"),
   WOW("Iron rusts and crumbles. Aluminium quietly grows a <b>thin invisible shield</b> on its own surface the instant air touches it — and then the weather can do its worst. That's why window frames, ladders and aeroplanes made of it last and last."),
   NOTE("Charlotte's Secret Notebook · SOLVED!","Aluminium doesn't rust — it grows its own invisible shield and shrugs off rain and years. Light AND tough. No wonder it's everywhere. 🛡️"),
 ]),
 ("c7","CHAPTER 7","Melted, and Born Again","pages 53-60",[
   P("hi_c7_melt","Otto dropped a crumpled can into the crucible. It melted into a bright silver pool — then poured out as a brand-new bar.","The can came BACK as something new!",None,"glug","#c8621f"),
   P("hi_c7_forever","\"You can do that forever,\" he grinned. \"And melting it again takes only a tiny sip of power — about a twentieth of the first time.\"","So the SECOND time is nearly free?!"),
   WOW("Here's the loveliest bit. Aluminium can be <b>melted down and reborn again and again, forever</b>, without getting worse. And recycling it uses only about <b>5% of the electricity</b> that making it from red earth did. The hungry metal, once made, becomes the thriftiest metal there is. ♻️"),
   NOTE("Charlotte's Secret Notebook","Aluminium can be melted and remade FOREVER, and doing so uses only about 5% of the original electricity. The metal never really dies — it just changes shape. ♻️"),
 ]),
 ("c8","CHAPTER 8 · THE BIG DISCOVERY","The Giant That Frees the Metal","pages 61-70",[
   P("hi_c8_reveal","Otto led Charlotte to a viewpoint: a red mine, a power station and a smelter, all standing together.","Who does ALL of this at once?"),
   P("hi_c8_1958","\"Back in 1958,\" said Otto, \"India built its first great aluminium works right here, on an empty plain.\"","They started with nothing but red dirt!"),
   P("hi_c8_scale","\"It grew and grew — its own mines, its own power, its own smelters, all in one long chain.\"","One company doing EVERY step!"),
   WOW("A \"company\" can be a giant shared job. <b>Hindalco</b> began in 1958 and grew into one of the world's great aluminium makers — because it does the <b>whole chain</b>: it owns the red earth, it makes its own electricity, and it smelts at enormous scale."),
   TL([("1958","India's first great aluminium works begins on an empty plain."),
       ("Over decades","It adds its own bauxite mines and its own power stations."),
       ("Today","One of the world's biggest aluminium makers — earth, power and smelter in one chain."),
       ("Tomorrow","Cleaner power and more recycling — the 5% metal. ♻️")]),
   NOTE("Charlotte's Secret Notebook","Hindalco (1958) grew into one of the world's biggest aluminium makers by owning EVERY step: the red earth, the electricity, and the smelter. 🏆"),
 ]),
 ("c9","CHAPTER 9","The Castle of Earth and Power","pages 71-80",[
   P("hi_c9_castle","Two kind old men appeared with a glow. Warren pointed at a castle standing on red earth, lit by its own power lines. \"What keeps rivals out, Charlotte?\"","Walls! But what kind?"),
   MOAT([("🟥","Wall One: It Owns the Red Earth","The bauxite lies under its own land. You cannot free a metal you cannot dig — and the good red earth is already spoken for.",False),
         ("⚡","Wall Two: It Owns the Power","The metal needs a river of electricity. Hindalco makes its own, so it isn't at the mercy of whoever sells it.",False),
         ("🏭","Wall Three: Giant Scale","Mines, power stations, smelters and decades of know-how, all linked in one chain. A rival can't build that overnight.",False),
         ("⚠️","The Crack in the Wall","It is an energy-hungry business. If power gets dearer — or the metal's world price falls — the profits get squeezed hard. Hunger is expensive.",True)]),
   P("hi_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 metal giant strong, imagine how it could FADE — power costs running away, borrowing too much to build, or letting rivals recycle cheaper than you smelt — then carefully avoid each one, and lean into the 5% metal."),
   P("hi_c9_verdict","Warren nodded. \"It owns the earth, the power and the scale — a mighty castle, so long as it keeps that hunger for electricity under control.\"","I SEE the whole picture!"),
   NOTE("Charlotte's Secret Notebook · The Big Secret","Hindalco is hard to copy: it OWNS the red earth, it MAKES its own power, and it works at GIANT scale. But it's an energy-hungry business — costly power squeezes it. Charlie's trick: picture how you'd lose (dear power, too much borrowing), then never do it. Invert! 🏰"),
 ]),
 ("c10","CHAPTER 10","The Metal That Flies","pages 81-88",[
   P("hi_c10_wake","Charlotte woke in her own bed. The red plateau was gone… but the silver can on her desk gleamed softly.","Was it real? It FELT real…"),
   P("hi_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 metal sleeping in the earth. Well done."'),
   P("hi_c10_look","She ran outside at dusk. A plane crossed the sky, a window frame gleamed, a can shone on the step — all of it, once, was red mud.","It was red earth the whole time — I just couldn't see it!"),
   WOW("Next time a plane goes over, you'll know the secret: it was once <b>red earth</b>. Lightning set the metal free, and the metal turned out to be light enough to fly, tough enough to last, and generous enough to come back again and again. That's <b>the metal that flies.</b> ✈️♻️"),
   NOTE("Charlotte's Secret Notebook · What I Learned","➊ Aluminium hides inside red earth called BAUXITE.<br>➋ ELECTROLYSIS — pushing electricity through it — is the only key that frees it, and it's very hungry.<br>➌ The metal is LIGHT (planes fly) and never RUSTS (its own invisible shield).<br>➍ It can be melted and reborn FOREVER, using only ~5% of the power. ♻️<br>➎ Hindalco owns the earth, the power and the scale; but Charlie's trick — picture how you'd lose (costly power), then don't. 💛"),
 ]),
]

HOOK=("hi_c1_swirl","EVERY ORDINARY THING HIDES A SECRET.",
 "Charlotte found a metal sleeping in the mud. But the compass is twitching again — toward the little glass rectangle in everyone's pocket that seems to know everything. What is really going on in there?",
 "NEXT ADVENTURE · The Glass That Thinks →")

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 METAL HIDES IN THE RED EARTH</text>
<g><rect x="70" y="112" width="150" height="90" rx="12" fill="#c0492f" stroke="#171717" stroke-width="4"/><text x="145" y="102" text-anchor="middle" font-family="Baloo 2" font-size="14" fill="#c0492f">RED EARTH</text><text x="145" y="165" text-anchor="middle" font-family="Bangers" font-size="24" fill="#f6b53f">bauxite</text><text x="145" y="235" text-anchor="middle" font-family="Nunito" font-size="13" fill="#555">the metal is locked inside</text></g>
<g stroke="#2f6fd0" stroke-width="5" fill="#2f6fd0"><line x1="230" y1="150" x2="330" y2="150" stroke-dasharray="10 8"/><path d="M326 141 L344 150 L326 159Z"/></g>
<text x="280" y="135" text-anchor="middle" font-family="Baloo 2" font-size="12" fill="#2f6fd0">electricity</text>
<text x="280" y="182" text-anchor="middle" font-family="Nunito" font-size="12" fill="#555">a LOT of it</text>
<g><rect x="350" y="112" width="150" height="90" rx="12" fill="#fff" stroke="#171717" stroke-width="4"/><text x="425" y="102" text-anchor="middle" font-family="Baloo 2" font-size="14" fill="#2f6fd0">ELECTROLYSIS</text><text x="425" y="165" text-anchor="middle" font-family="Bangers" font-size="26" fill="#2f6fd0">frees it</text><text x="425" y="235" text-anchor="middle" font-family="Nunito" font-size="13" fill="#555">the grip lets go</text></g>
<g stroke="#2aa15a" stroke-width="5" fill="#2aa15a"><line x1="510" y1="150" x2="610" y2="150" stroke-dasharray="10 8"/><path d="M606 141 L624 150 L606 159Z"/></g>
<g><rect x="630" y="112" width="140" height="90" rx="12" fill="#dfe6ee" stroke="#171717" stroke-width="4"/><text x="700" y="102" text-anchor="middle" font-family="Baloo 2" font-size="16" fill="#37414d">ALUMINIUM</text><text x="700" y="165" text-anchor="middle" font-family="Bangers" font-size="24" fill="#37414d">light metal</text><text x="700" y="235" text-anchor="middle" font-family="Nunito" font-size="13" fill="#555">light, never rusts, reborn forever</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">Red earth + a river of ELECTRICITY &#8594; silver metal &#8594; light enough to FLY, and it never rusts.</text>
<text x="410" y="343" text-anchor="middle" font-family="Nunito" font-size="13" fill="#555">Melt it down and it is born again — using only about 5% of the electricity.</text>
</svg><div class="figcap">Aluminium hides in red bauxite; electricity sets it free; the metal is light, rust-proof and endlessly reborn.</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_otto"); 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/hindalco/_head.html").read()
    tail=open("/root/omahaindia.com/comics/site/book/hindalco/_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()
