#!/usr/bin/env python3
# Book 37 (HCL Technologies) — THE HANDS INSIDE THE MACHINE. Science->business: machines don't run
# themselves — every big computer system needs hidden HANDS to build, watch, repair and upgrade it
# (a pit crew for a race car, a body's immune system quietly fixing things) -> the giant that runs
# the world's computer systems for them: maintenance as invisible heroism.
import os
ART="/root/omahaindia.com/comics/site/book/hcl/art"
OUT="/root/omahaindia.com/comics/site/book/hcl/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"
DEAN=("Dean, a warm friendly Western SYSTEMS ENGINEER, NOT Indian, neat trimmed beard, calm capable smile, "
"navy polo shirt with a badge lanyard around his neck, a screwdriver in one hand and a glowing tablet in the other")

# name -> (w,h,seed,prompt,ref). ref set -> Seedream character; None -> flux scene. Ritual panels copied by mkbook.
NEW={
 "00_cover":(1024,1180,3700,f"{STYLE}. BOOK COVER, {CHARLOTTE} standing with {DEAN} inside a vast glowing hall of humming computer machines, tall racks of blinking blue-and-amber lights stretching back, she reaches up to touch a warm ribbon of light flowing between the machines like a living pulse, wonder, cinematic","charlotte"),
 "_ref_dean":(1024,1024,3701,f"{STYLE}. clean friendly character portrait, {DEAN}, plain soft warm background, calm capable smile, head and shoulders",None),
 # Ch1
 "hc_c1_coin":(1024,720,3710,f"{STYLE}. {CHARLOTTE} at home, Grandpa Ben's glowing brass compass twitching between a frozen dark computer screen and a smoothly glowing bright screen on the table, EXPRESSION puzzled and intrigued, cozy lamp light","charlotte"),
 "hc_c1_diary":(1024,720,3711,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 pair of gentle helping hands, no people",None),
 "hc_c1_swirl":(1024,720,3712,f"{STYLE}. {CHARLOTTE} pulled into a swirling spiral of golden light and blue circuit-sparks from a glowing diary, EXPRESSION thrilled, magical","charlotte"),
 # Ch2 — arrive at the machine hall, meet Dean
 "hc_c2_arrive":(1024,720,3713,f"{STYLE}. {CHARLOTTE} landing wide-eyed inside an enormous humming hall of computer machines, rows of tall racks with blinking lights stretching away into the distance, cool blue glow, EXPRESSION awe and delight","charlotte"),
 "hc_c2_dean":(1024,720,3714,f"{STYLE}. {DEAN} warmly welcoming {CHARLOTTE} in the machine hall, giving a friendly wave with his screwdriver, EXPRESSION Charlotte shy happy smile; keep the SAME systems engineer from the reference, same navy polo, same badge lanyard, same screwdriver and glowing tablet","dean"),
 "hc_c2_pit":(1024,720,3715,f"{STYLE}. a vast server hall seen down a long aisle, towering racks of humming machines with rivers of blinking blue and amber lights, tiny engineer figures for scale, powerful and awe-inspiring, no faces close up",None),
 # Ch3 — machines don't run themselves: a race car needs a pit crew
 "hc_c3_leaf":(1024,720,3716,f"{STYLE}. {DEAN} kneeling to show {CHARLOTTE} a single sleek race car up close, its engine open, a warm spark of energy inside it, EXPRESSION Charlotte fascinated leaning in; SAME systems engineer, navy polo, badge lanyard, screwdriver and tablet","dean"),
 "hc_c3_forest":(1024,720,3717,f"{STYLE}. a busy pit crew swarming around a race car in a bright pit lane, many hands changing tyres and checking the engine all at once, teamwork and speed, energetic, no faces close up",None),
 "hc_c3_store":(1024,720,3718,f"{STYLE}. a friendly close up of a single computer machine with tiny gentle cartoon hands tending it — tightening, polishing, checking a glowing dial — playful science, no people",None),
 # Ch4 — the watchers who never sleep: monitoring like an immune system
 "hc_c4_sink":(1024,720,3719,f"{STYLE}. {CHARLOTTE} watching in wonder as deep inside a humming machine one tiny light quietly flickers from calm blue to a worried amber, a hidden fault beginning, EXPRESSION alert and thoughtful, cool glow","charlotte"),
 "hc_c4_press":(1024,720,3720,f"{STYLE}. a magical cutaway of a great control room, a wall of glowing screens with gentle heartbeat pulse-lines, calm watchers keeping vigil around the clock like a body's watchful immune cells, warm-and-cool glow, no faces close up",None),
 "hc_c4_rock":(1024,720,3721,f"{STYLE}. a beautiful close up of a single tiny amber warning spark caught early on a glowing monitor pulse-line, a gentle hand reaching toward it just in time, dark rim bright center, no people",None),
 # Ch5 — the healing hands: repair before anyone notices
 "hc_c5_burn":(1024,720,3722,f"{STYLE}. a small fault flaring up inside a machine, a bright spark and a puff of worried light escaping a loose part, urgent but not scary, glowing embers of a glitch, no people",None),
 "hc_c5_boil":(1024,720,3723,f"{STYLE}. {DEAN} showing {CHARLOTTE} how quick sure hands swap a glowing part and calm the machine's light back to steady blue, fixed before anyone noticed, EXPRESSION Charlotte relieved 'aha'; SAME systems engineer, navy polo, badge lanyard, screwdriver and tablet","dean"),
 # Ch6 — making it smarter: build and upgrade to harder jobs
 "hc_c6_spin":(1024,720,3724,f"{STYLE}. {CHARLOTTE} watching engineers lift a bright new smarter part into a machine, the whole rack blooming into faster brighter light, her ponytails lit by the glow, EXPRESSION awed and excited, bright hall","charlotte"),
 "hc_c6_electric":(1024,720,3725,f"{STYLE}. bright ribbons of light racing out of an upgraded glowing machine along wires toward a city, screens and devices everywhere lighting up faster and smoother, magical, no people",None),
 # Ch7 — holding up the world, for everyone
 "hc_c7_everyone":(1024,720,3726,f"{STYLE}. a joyful busy city running smoothly — a bank, an airport, a hospital, a school, phones and screens — all glowing and working perfectly, warm togetherness, no faces close up",None),
 "hc_c7_half":(1024,720,3727,f"{STYLE}. a warm storybook map of the whole world at night, countless glowing systems humming across it, gentle threads of light flowing back to one great control campus, gentle and grand, no people",None),
 # Ch8 — reveal HCL Technologies
 "hc_c8_reveal":(1024,720,3728,f"{STYLE}. {CHARLOTTE} and {DEAN} standing proudly before a vast modern technology campus glowing against a blue sky, glass towers and humming server halls, EXPRESSION proud recognition; SAME systems engineer, navy polo, badge lanyard, screwdriver and tablet","charlotte"),
 "hc_c8_1975":(1024,720,3729,f"{STYLE}. warm sepia 1970s scene, a few hopeful young engineers building the very first computers by hand at a simple workbench, big old machines and hand tools, inspiring, no text",None),
 "hc_c8_scale":(1024,720,3730,f"{STYLE}. a mighty modern technology campus at golden hour, glass towers and vast glowing server halls, thousands of engineers, one of the world's biggest keepers of computer systems, proud and grand, no people",None),
 # Ch10 (ch9 uses ritual castle/invert/verdict; ch10 uses ritual wake/diary)
 "hc_c10_look":(1024,720,3731,f"{STYLE}. {CHARLOTTE} outside in the city looking with wonder as every screen, cash machine, traffic light and glowing phone around her works smoothly, knowing hidden hands keep each one alive, 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 Screen That Wouldn't Wake","pages 1-8",[
   P("hc_c1_coin","Back home, Grandpa Ben's compass twitched again — pointing between a frozen dark screen and one that glowed and worked just fine.","One screen is dead, one is happy… what's the difference?",None,"twitch"),
   P("hc_c1_diary","The old diary fell open. A new line shimmered in Grandpa Ben's hand.",None,'"Find the hidden hands that keep the machines alive."'),
   WOW("A screen doesn't fix itself, and a giant computer doesn't run itself. Somewhere, quietly, someone is building it, watching it, and mending it — or it stops. Who are these hidden hands, and why does the whole world lean on them? That's the puzzle of this whole adventure."),
   P("hc_c1_swirl","Golden light swirled up and pulled Charlotte in.","Here we GO!",None,"WHOOSH","#2563eb"),
   NOTE("Charlotte's Secret Notebook","Two BIG questions:<br>➊ Why does one screen work and the other stay frozen?<br>➋ Grandpa Ben says <i>hidden hands</i> keep machines alive. Whose hands — and where are they hiding? 🖐️"),
 ]),
 ("c2","CHAPTER 2","The Hall of Humming Machines","pages 9-16",[
   P("hc_c2_arrive","One blink, and she stood in the biggest room she'd ever seen — rows of tall machines humming softly, blinking with a thousand little lights.","It's a whole CITY made of computers!"),
   P("hc_c2_dean","A friendly man with a badge waved a screwdriver. \"I'm Dean, a systems engineer. My job is keeping all these machines alive and well.\"","You're their… DOCTOR?!"),
   P("hc_c2_pit","Down the aisle, the racks stretched further than she could see, each one warm and busy.","So many machines — and someone looks after ALL of them?","Stick with me, kiddo."),
   NOTE("Charlotte's Secret Notebook","Dean is a systems engineer, and he grins like he has a secret — just like the other guides did. He keeps the humming machines alive. Okay Dean… show me how! ✨"),
 ]),
 ("c3","CHAPTER 3","Machines Don't Run Themselves","pages 17-26",[
   P("hc_c3_leaf","Dean opened up a sleek race car. \"A machine is like this — full of power, but it can't look after itself. Push it hard and something always needs care.\"","A machine is like a RACE CAR!"),
   P("hc_c3_forest","\"So every fast car has a pit crew,\" he said. \"Hands that fuel it, fix it, change its tyres — over and over, so it never stops.\"","A whole team, just to keep ONE car going!"),
   P("hc_c3_store","\"Big computers are the same. They need a crew of hands, always, or they slow down and freeze.\"","The machine can't do it alone — it needs HANDS!",None,"tend","#2563eb"),
   WOW("Here's the first secret! 💡 A powerful machine is like a <b>race car</b>: on its own it stops. It needs a <b>pit crew</b> — hands to build it, tend it and keep it running. Big computers are exactly the same. Left alone, even the mightiest machine quietly grinds to a halt."),
   ("diagram",),
   NOTE("Charlotte's Secret Notebook","A machine is like a race car — full of power but helpless alone. It needs a pit crew of hands to keep it running. Big computers need the same: a crew that never stops. 🏎️🖐️"),
 ]),
 ("c4","CHAPTER 4","The Watchers Who Never Sleep","pages 27-36",[
   P("hc_c4_sink","\"First, we WATCH,\" said Dean. Deep in a machine, one calm blue light flickered to worried amber — a tiny trouble, just beginning.","Something's going wrong in there!"),
   P("hc_c4_press","\"Day and night, we watch the machines' heartbeats on our screens — like the tiny guards inside your body that spot a cold before you even sneeze.\"","Like an IMMUNE SYSTEM for machines!",None,"beep","#2aa15a"),
   P("hc_c4_rock","\"Catch the trouble while it's a tiny spark,\" he smiled, \"and you can fix it before it ever becomes a fire.\"","Spot it small — stop it BIG!"),
   WOW("The hidden hands don't just fix — first they <b>watch</b>, day and night. Screens show each machine's heartbeat, and a good crew spots a tiny amber spark long before it grows. It's like a body's <b>immune system</b>: quiet guards, always on duty, catching trouble early."),
   NOTE("Charlotte's Secret Notebook","The hands WATCH the machines all day and night, reading their heartbeats on screens. Like an immune system, they catch a tiny spark of trouble early — before it becomes a fire. 🛡️"),
 ]),
 ("c5","CHAPTER 5","The Healing Hands","pages 37-44",[
   P("hc_c5_burn","Suddenly a part sparked and flared. A worried light puffed out of the machine.","Uh oh — something BROKE!",None,"ZZZT","#2563eb"),
   P("hc_c5_boil","Quick, sure hands swapped the part and calmed the light back to steady blue. \"Fixed,\" said Dean, \"before anyone even noticed.\"","Nobody even KNEW it broke!"),
   WOW("When something breaks, the hidden hands <b>repair it fast</b> — often before a single person notices anything went wrong. That's the strange magic of this job: when it's done well, it's <b>invisible</b>. Nothing seems to happen. The machine simply keeps working."),
   NOTE("Charlotte's Secret Notebook","When a part breaks, quick hands swap it and calm the machine — usually before anyone notices. The best repairs are INVISIBLE: everything just keeps working. That's quiet heroism. 🔧"),
 ]),
 ("c6","CHAPTER 6","Making It Smarter","pages 45-52",[
   P("hc_c6_spin","Engineers lifted a bright new part into a rack. The whole machine bloomed brighter and faster.","It just got SMARTER!"),
   P("hc_c6_electric","\"We don't only mend,\" said Dean. \"We keep building — making the machines faster, cleverer, better every year.\"","So the hands make it GROW, not just stay alive!"),
   WOW("The hands don't only keep machines alive — they keep making them <b>better</b>: faster, smarter, ready for harder jobs. Build → watch → repair → upgrade, then build again. That's the whole loop that keeps the world's computers strong. What a job!"),
   NOTE("Charlotte's Secret Notebook · SOLVED!","The hidden hands do FOUR things, round and round: BUILD it, WATCH it, REPAIR it, and UPGRADE it smarter. Not just keeping machines alive — making them better every year! ⚙️"),
 ]),
 ("c7","CHAPTER 7","Holding Up the World","pages 53-60",[
   P("hc_c7_everyone","Dean swept his arm across the city. A bank, an airport, a hospital, a school — all humming along perfectly.","EVERYTHING runs on machines like these?!"),
   P("hc_c7_half","\"When you tap your card, catch a flight, or open an app,\" said Dean, \"hidden hands somewhere are keeping that machine alive for you.\"","The whole world leans on hands I never see!"),
   WOW("This isn't a small thing. Banks, airlines, hospitals, shops and phones — almost every big thing you use runs on machines that <b>someone, somewhere</b> is quietly keeping alive. When it all works, you never think about it. That's the whole point of the hidden hands."),
   NOTE("Charlotte's Secret Notebook","Banks, airports, hospitals, shops, apps — nearly everything big runs on computers that hidden hands keep alive. When it works, you never notice. The whole world quietly leans on them. 🌏"),
 ]),
 ("c8","CHAPTER 8 · THE BIG DISCOVERY","The Giant That Runs the Machines","pages 61-70",[
   P("hc_c8_reveal","Dean led Charlotte to a viewpoint over a vast glowing technology campus.","Who does ALL of this, for everyone?"),
   P("hc_c8_1975","\"It started in 1976,\" said Dean, \"with a few young engineers building computers by hand at a simple workbench.\"","From a workbench… to THIS?!"),
   P("hc_c8_scale","\"It grew and grew — until it ran computer systems for companies all across the WORLD.\"","One giant crew, for the whole planet's machines!"),
   WOW("A \"company\" can be a giant shared crew. <b>HCL Technologies</b> began in 1976 building computers by hand, and grew into one of the world's biggest keepers of computer systems — the <b>hidden hands</b> for banks, airlines and companies across the globe."),
   TL([("1976","A few engineers begin building computers by hand at a simple workbench."),
       ("Over decades","It grows into a giant that runs computer systems for companies worldwide."),
       ("Today","Its hidden hands keep countless machines alive across the whole world."),
       ("Tomorrow","It climbs to harder, smarter work — teaching machines to help fix themselves. 🤖")]),
   NOTE("Charlotte's Secret Notebook","HCL Technologies (1976) began with a few engineers at a workbench and grew into a giant that runs the world's computer systems. It is the hidden hands for companies everywhere. 🏆"),
 ]),
 ("c9","CHAPTER 9","The Castle Made of Trust","pages 71-80",[
   P("hc_c9_castle","Two kind old men appeared with a glow. Warren pointed at a castle standing on a field of humming machines. \"What keeps rivals out, Charlotte?\"","Walls! But what kind?"),
   MOAT([("🤝","Wall One: Sticky Trust","Once a company lets you run its machines, switching to someone else is scary and painful. You know their systems inside out — so they stay, year after year.",False),
         ("🏭","Wall Two: Giant Scale","Thousands of skilled engineers and know-how across every industry, built up over decades. A rival can't gather that overnight.",False),
         ("🔗","Wall Three: Woven Into Everything","When a bank's or airline's whole system leans on your hands, you're very hard to pull out. The trust is wired into everything they do.",False),
         ("⚠️","The Crack in the Wall","The simplest watching-and-fixing work can be done cheaper by rivals — or by clever robots. The crew must keep climbing to harder, smarter jobs, or the easy work slips away.",True)]),
   P("hc_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 systems giant strong, imagine how it could FADE — clinging to only cheap, simple work while robots and rivals do it cheaper — then carefully avoid that, and keep climbing to harder, smarter jobs early."),
   P("hc_c9_verdict","Warren nodded. \"It's trusted, it's giant, and it's woven into everything — a mighty castle, so long as it keeps climbing to smarter work.\"","I SEE the whole picture!"),
   NOTE("Charlotte's Secret Notebook · The Big Secret","HCL is hard to copy: companies TRUST it, it's GIANT, and it's WOVEN into everything they do. But it must keep CLIMBING — the simple work can be done cheaper, so it must chase harder, smarter jobs. Charlie's trick: picture how you'd lose (only cheap work), then never do it. Invert! 🏰"),
 ]),
 ("c10","CHAPTER 10","The Hands We Never See","pages 81-88",[
   P("hc_c10_wake","Charlotte woke in her own bed. The great machine hall was gone… but her little screen on the desk glowed softly, wide awake.","Was it real? It FELT real…"),
   P("hc_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 hands that keep the machines alive. Well done."'),
   P("hc_c10_look","She ran outside. Every screen, every cash machine, every glowing traffic light — all of it, quietly, was kept alive by hands she'd never see.","The hidden hands were everywhere — I just couldn't see them!"),
   WOW("Next time a screen lights up and simply works, you'll know the secret: somewhere, <b>hidden hands</b> are keeping it alive. They build, they watch, they repair, they upgrade — quietly, invisibly, for the whole world. That's <b>the hands inside the machine.</b> 🖐️💻"),
   NOTE("Charlotte's Secret Notebook · What I Learned","➊ A machine is like a race car — powerful, but helpless without a pit crew of hands.<br>➋ The hidden hands WATCH day and night, like an immune system, catching trouble early.<br>➌ They REPAIR fast — often before anyone notices — and keep UPGRADING machines smarter.<br>➍ Nearly the whole world's banks, flights and phones lean on them.<br>➎ HCL runs the world's machines; but Charlie's trick — picture how you'd lose (only cheap work), then keep climbing to harder, smarter jobs. 💛"),
 ]),
]

HOOK=("hc_c1_swirl","EVERY ORDINARY THING HIDES A SECRET.",
 "Charlotte found the hidden hands that keep the world's machines alive. But the compass is twitching again — toward the little pill that made a sick friend well again. Where do medicines come from, and who dreams them up?",
 "NEXT ADVENTURE · The Medicine Makers →")

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="#2563eb">MACHINES DON'T RUN THEMSELVES</text>
<g><rect x="70" y="90" width="150" height="80" rx="12" fill="#fff" stroke="#171717" stroke-width="4"/><text x="145" y="82" text-anchor="middle" font-family="Baloo 2" font-size="14" fill="#2563eb">BUILD</text><text x="145" y="140" text-anchor="middle" font-family="Bangers" font-size="24" fill="#2563eb">make it</text></g>
<g stroke="#2aa15a" stroke-width="5" fill="#2aa15a"><line x1="228" y1="130" x2="298" y2="130" stroke-dasharray="10 8"/><path d="M294 121 L312 130 L294 139Z"/></g>
<g><rect x="320" y="90" width="150" height="80" rx="12" fill="#fff" stroke="#171717" stroke-width="4"/><text x="395" y="82" text-anchor="middle" font-family="Baloo 2" font-size="14" fill="#2aa15a">WATCH</text><text x="395" y="140" text-anchor="middle" font-family="Bangers" font-size="24" fill="#2aa15a">guard it</text></g>
<g stroke="#c8621f" stroke-width="5" fill="#c8621f"><line x1="478" y1="130" x2="548" y2="130" stroke-dasharray="10 8"/><path d="M544 121 L562 130 L544 139Z"/></g>
<g><rect x="570" y="90" width="150" height="80" rx="12" fill="#fff" stroke="#171717" stroke-width="4"/><text x="645" y="82" text-anchor="middle" font-family="Baloo 2" font-size="14" fill="#c8621f">REPAIR</text><text x="645" y="140" text-anchor="middle" font-family="Bangers" font-size="24" fill="#c8621f">mend it</text></g>
<g stroke="#37414d" stroke-width="5" fill="none"><path d="M645 174 L645 232 L145 232 L145 178" stroke-dasharray="10 8"/></g>
<path d="M136 182 L145 164 L154 182Z" fill="#37414d"/>
<text x="410" y="224" text-anchor="middle" font-family="Baloo 2" font-size="13" fill="#37414d">UPGRADE — make it smarter, then start again</text>
<rect x="70" y="272" width="680" height="80" rx="9" fill="#fff" stroke="#171717" stroke-width="3"/>
<text x="410" y="300" text-anchor="middle" font-family="Nunito" font-size="14" fill="#123">A big machine is like a race car: without a pit crew of HANDS it stops.</text>
<text x="410" y="322" text-anchor="middle" font-family="Nunito" font-size="13" fill="#555">The hidden hands build it, watch it, repair it and upgrade it — round and round, so it never quits.</text>
<text x="410" y="343" text-anchor="middle" font-family="Nunito" font-size="13" fill="#555">When they do it well, nothing seems to happen at all. That is the quiet heroism of maintenance.</text>
</svg><div class="figcap">Machines can't run themselves: hidden hands build, watch, repair and upgrade them in a never-ending loop.</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_dean"); 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/hcl/_head.html").read()
    tail=open("/root/omahaindia.com/comics/site/book/hcl/_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()
