#!/usr/bin/env python3
# Book 28 (Power Grid Corp) — THE HIGHWAYS OF LIGHT. Science->business: pushing power far LOSES it as heat
# -> transformers push the voltage very HIGH so it travels thin and far, then step it back down safely for homes
# -> the grid must balance every second (make = use) -> the company that owns the highways every power maker must use.
import os
ART="/root/omahaindia.com/comics/site/book/powergrid/art"
OUT="/root/omahaindia.com/comics/site/book/powergrid/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"
MILES=("Miles, a warm friendly Western GRID ENGINEER, NOT Indian, tall lean build, easy confident smile, "
"a bright yellow hard hat, a navy work jacket, a handheld radio 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,2800,f"{STYLE}. BOOK COVER, {CHARLOTTE} standing with {MILES} at the foot of a colossal steel transmission tower, a glowing river of light streaming along the wires away over hills toward a bright city, golden sunset sky, wonder, cinematic","charlotte"),
 "_ref_miles":(1024,1024,2801,f"{STYLE}. clean friendly character portrait, {MILES}, plain soft warm background, easy confident smile, head and shoulders",None),
 # Ch1
 "pg_c1_coin":(1024,720,2810,f"{STYLE}. {CHARLOTTE} at home, Grandpa Ben's glowing brass compass twitching between a glowing lamp on the table and a faraway lit-up power station seen through the window, EXPRESSION puzzled and intrigued, cozy lamp light","charlotte"),
 "pg_c1_diary":(1024,720,2811,f"{STYLE}. an open magical diary glowing warm gold on a desk, a thin bright ribbon of light rising from the page and racing away toward a tiny distant tower, no people",None),
 "pg_c1_swirl":(1024,720,2812,f"{STYLE}. {CHARLOTTE} pulled into a swirling spiral of golden light and crackling blue sparks from a glowing diary, EXPRESSION thrilled, magical","charlotte"),
 # Ch2 — arrive at the towers, meet Miles
 "pg_c2_arrive":(1024,720,2813,f"{STYLE}. {CHARLOTTE} landing wide-eyed at the foot of a giant steel lattice transmission tower, its wires marching away over green hills to the horizon, EXPRESSION awe and delight, bright daylight","charlotte"),
 "pg_c2_miles":(1024,720,2814,f"{STYLE}. {MILES} warmly welcoming {CHARLOTTE} at the tower, tipping his yellow hard hat, EXPRESSION Charlotte shy happy smile; keep the SAME engineer from the reference, same navy work jacket and yellow hard hat and handheld radio","miles"),
 "pg_c2_line":(1024,720,2815,f"{STYLE}. a long line of enormous steel transmission towers striding across open countryside all the way to a distant city, wires shining in the sun, powerful and awe-inspiring, no faces close up",None),
 # Ch3 — power fades over distance: it leaks away as heat
 "pg_c3_far":(1024,720,2816,f"{STYLE}. {MILES} kneeling to show {CHARLOTTE} a long thin wire with a bright lamp at the near end and a sadly dim lamp at the far end, EXPRESSION Charlotte fascinated leaning in; SAME engineer, navy jacket, yellow hard hat","miles"),
 "pg_c3_heat":(1024,720,2817,f"{STYLE}. a magical close up of electricity squeezing along a crowded wire, tiny warm puffs of heat escaping from the wire as the light leaks away, playful science, no people",None),
 "pg_c3_crowd":(1024,720,2818,f"{STYLE}. a friendly storybook picture of a narrow lane packed with too many jostling glowing sparks, warm heat rising from the crush, playful science, no people",None),
 # Ch4 — transformers push voltage very high so it travels thin and far
 "pg_c4_transformer":(1024,720,2819,f"{STYLE}. {CHARLOTTE} watching a big humming transformer glow as a slow fat river of light is squeezed into a fast thin bright thread, EXPRESSION amazed and thoughtful, dramatic evening light","charlotte"),
 "pg_c4_push":(1024,720,2820,f"{STYLE}. a magical diagram-like scene of a giant gentle hand pushing light into a slim shining thread that shoots far across a valley, arrows of push, warm glow, no people",None),
 "pg_c4_travel":(1024,720,2821,f"{STYLE}. a beautiful close up of a single high wire carrying a slim streak of brilliant light, cool and calm with almost no heat escaping, dark rim bright center, no people",None),
 # Ch5 — step it back down, safely, for homes
 "pg_c5_step":(1024,720,2822,f"{STYLE}. a friendly green substation transformer gently turning a fierce bright thread of light back into a soft calm warm glow, safe and cozy, no people",None),
 "pg_c5_home":(1024,720,2823,f"{STYLE}. {MILES} showing {CHARLOTTE} how the calm gentle power reaches a cozy home and lights a warm lamp and a kettle, EXPRESSION Charlotte delighted 'aha'; SAME engineer, navy jacket, yellow hard hat","miles"),
 # Ch6 — the grid must balance every second: make = use
 "pg_c6_balance":(1024,720,2824,f"{STYLE}. {CHARLOTTE} watching a giant magical balance scale, glowing power stations on one pan and glowing lit homes on the other, perfectly level, EXPRESSION awed and excited, bright hall","charlotte"),
 "pg_c6_room":(1024,720,2825,f"{STYLE}. a bright calm control room with a huge glowing wall map of a country criss-crossed with light lines, engineers watching from behind, warm hi-tech, no faces close up",None),
 # Ch7 — the highways every maker must use
 "pg_c7_everyone":(1024,720,2826,f"{STYLE}. a joyful scene where a coal plant, a hydro dam, a solar farm and a wind farm all send their light into the SAME shining highway of wires, warm togetherness, no faces close up",None),
 "pg_c7_map":(1024,720,2827,f"{STYLE}. a warm storybook map of India at night criss-crossed by glowing rivers of light joining every corner into one bright web, gentle and grand, no people",None),
 # Ch8 — reveal Power Grid
 "pg_c8_reveal":(1024,720,2828,f"{STYLE}. {CHARLOTTE} and {MILES} standing proudly before a mighty substation and a line of towers glowing against a blue sky, EXPRESSION proud recognition; SAME engineer, navy jacket, yellow hard hat","charlotte"),
 "pg_c8_1989":(1024,720,2829,f"{STYLE}. warm sepia late-1980s scene, separate little regional power networks being stitched together into one great national web of wires, hopeful engineers and old maps, inspiring, no text",None),
 "pg_c8_scale":(1024,720,2830,f"{STYLE}. a magnificent modern high-voltage corridor at golden hour, colossal towers and shining wires stretching to the horizon, one of the greatest grids on Earth, proud and grand, no people",None),
 # Ch10 (ch9 uses ritual castle/invert/verdict; ch10 uses ritual wake/diary)
 "pg_c10_look":(1024,720,2831,f"{STYLE}. {CHARLOTTE} outside at dusk looking up with wonder at the quiet wires overhead glowing faintly against the sunset, every window in the street warm behind her, 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 Light That Came From Far Away","pages 1-8",[
   P("pg_c1_coin","Back home, Grandpa Ben's compass twitched again — pointing between the lamp on the table and a tiny power station far, far away on the hill.","My lamp is HERE. The power is way over THERE?",None,"twitch"),
   P("pg_c1_diary","The old diary fell open. A new line shimmered in Grandpa Ben's hand.",None,'"Find the road the light takes to reach you."'),
   WOW("Your lamp glows in your room — but the machine that MAKES its power might be hundreds of kilometres away, past hills and rivers and towns. How does light-power travel that far without getting lost on the way? That's the puzzle of this whole adventure."),
   P("pg_c1_swirl","Golden light swirled up and pulled Charlotte in.","Here we GO!",None,"ZAAP","#c8621f"),
   NOTE("Charlotte's Secret Notebook","Two BIG questions:<br>➊ How does power travel SO far to reach my little lamp?<br>➋ Grandpa Ben says there's a <i>road</i> for light. Who builds a road like that? ⚡"),
 ]),
 ("c2","CHAPTER 2","The Giants With Wires in Their Arms","pages 9-16",[
   P("pg_c2_arrive","One blink, and she stood under the tallest steel giant she'd ever seen — its wires marching away over the hills forever.","They go on and ON — where do they END?"),
   P("pg_c2_miles","A cheerful man in a yellow hard hat waved. \"I'm Miles, a grid engineer. These aren't just wires, kiddo. They're HIGHWAYS.\"","Highways… for LIGHT?!"),
   P("pg_c2_line","Tower after tower strode across the countryside, carrying shining wires toward a city too far to see.","So the power drives all the way from there to my lamp?","Every single second of every day."),
   NOTE("Charlotte's Secret Notebook","Miles is a grid engineer, and he grins like he has a secret — just like the other guides did. He calls the wires 'highways of light'. Okay Miles… show me! ✨"),
 ]),
 ("c3","CHAPTER 3","The Power That Leaks Away","pages 17-26",[
   P("pg_c3_far","Miles ran a long thin wire between two lamps. The near lamp blazed. The far one barely glimmered.","The far lamp is going dim! Where did its power GO?"),
   P("pg_c3_heat","\"It didn't vanish,\" said Miles. \"It leaked out of the wire — as HEAT. Push power a long way and the road itself steals some.\"","The wire gets WARM by stealing it!"),
   P("pg_c3_crowd","\"Think of a narrow lane packed with pushing, shoving sparks. All that jostling makes heat — and heat is power wasted.\"","Too much crowding = too much waste!",None,"fizz","#c8621f"),
   WOW("Here's the first secret! 💡 Electricity doesn't travel for free. Push it down a wire and some of it <b>leaks away as heat</b> — the wire gets warm, and that warmth is power nobody gets to use. The farther you go, the more you lose. So how do you send power hundreds of kilometres and still have some left?"),
   ("diagram",),
   NOTE("Charlotte's Secret Notebook","Sending power far LOSES some of it — it turns into heat in the wire. Crowded, jostling electricity = warm wire = wasted power. Long distance is the enemy! 🔥"),
 ]),
 ("c4","CHAPTER 4","The Big Push","pages 27-36",[
   P("pg_c4_transformer","Miles thumped a humming grey box. \"This is a transformer. It takes a slow fat river of power and PUSHES it — very, very hard.\"","It's squeezing the river into a thread!"),
   P("pg_c4_push","\"That push has a name: VOLTAGE. Push harder, and the same power travels as a thin, fast thread instead of a jostling crowd.\"","Harder push, thinner thread!",None,"HUMMM","#37414d"),
   P("pg_c4_travel","\"A thin, uncrowded thread barely warms the wire at all — so it can run for hundreds of kilometres and hardly lose a drop.\"","Less crowding, less leaking — it goes FAR!"),
   WOW("Transformers <b>push the voltage very HIGH</b> — hundreds of thousands of volts. The same power then travels as a <b>thin, uncrowded thread</b> instead of a shoving crowd, so almost nothing leaks away as heat. High push = travels thin = travels FAR. That's the trick that makes long-distance power possible."),
   NOTE("Charlotte's Secret Notebook · SOLVED (part 1)","A TRANSFORMER pushes the voltage very high. High push makes the power travel thin and uncrowded, so it hardly heats the wire — and it can cross the whole country. ⚡🗺️"),
 ]),
 ("c5","CHAPTER 5","Gently, Now","pages 37-44",[
   P("pg_c5_step","At the far end sat a green substation. The fierce bright thread went in — and a soft, calm glow came out.","It's turning the push back DOWN!",None,"click","#2aa15a"),
   P("pg_c5_home","\"That huge push would be far too fierce for your house,\" said Miles. \"So we step it down — again and again — until it's gentle and safe.\"","High to travel… low to come home!"),
   WOW("A giant push is perfect for <b>travelling</b> and far too dangerous for a <b>home</b>. So substations <b>step the voltage back down</b>, step by step, until it's calm and safe enough for your lamp, your fan and your kettle. Up to fly, down to land."),
   NOTE("Charlotte's Secret Notebook","Push it UP to cross the country. Step it DOWN to enter a home. Transformers do both — the same power, made fierce for the road and gentle for the house. 🏠💡"),
 ]),
 ("c6","CHAPTER 6","The Great Balancing Act","pages 45-52",[
   P("pg_c6_balance","Miles showed her a giant scale: power being MADE on one side, power being USED on the other. Perfectly level.","They have to match EXACTLY?"),
   P("pg_c6_room","\"Every single second,\" he said. \"Make a little too much or too little, and the whole grid wobbles. So we watch, and nudge, and balance — forever.\"","Nobody ever gets to stop watching!"),
   WOW("Electricity can't wait around in the wires — it must be <b>used the instant it's made</b>. So the grid must balance every second: <b>make = use</b>. Someone switches on a kettle; somewhere a machine must push a tiny bit harder. It's the biggest balancing act in the country, and it never, ever pauses."),
   NOTE("Charlotte's Secret Notebook · SOLVED!","The whole chain: power station → transformer pushes voltage HIGH → travels thin and far → substation steps it DOWN → my lamp. And every second, MAKE must equal USE. ⚖️⚡"),
 ]),
 ("c7","CHAPTER 7","One Road, Everybody's Road","pages 53-60",[
   P("pg_c7_everyone","Miles pointed around: a coal plant, a dam, a solar farm, a wind farm — all pouring their light into the SAME shining wires.","They all use the same road!"),
   P("pg_c7_map","\"Sun in the west, wind in the south, coal in the east,\" said Miles. \"The highways carry it wherever the country needs it.\"","One web joining the whole country!"),
   WOW("It doesn't matter <b>who</b> makes the power — coal, water, sun or wind — every maker must send it down the <b>same highways</b> to reach the people who need it. One shared web, joining a whole nation, moving power from wherever it's made to wherever it's wanted."),
   NOTE("Charlotte's Secret Notebook","Every kind of power maker — coal, dams, solar, wind — pours into ONE shared web of wires. The road belongs to everybody, and everybody needs it. 🌏🔌"),
 ]),
 ("c8","CHAPTER 8 · THE BIG DISCOVERY","The Company That Owns the Highways","pages 61-70",[
   P("pg_c8_reveal","Miles led Charlotte to a viewpoint over a mighty substation and its endless line of towers.","Who BUILDS all of this?"),
   P("pg_c8_1989","\"In 1989,\" said Miles, \"India set up one company to stitch its separate little networks into a single national web.\"","One web, made from many!"),
   P("pg_c8_scale","\"It grew and grew — until it ran one of the greatest power highways on EARTH.\"","The world's biggest road for light!"),
   WOW("A \"company\" can be a giant shared job. <b>Power Grid Corporation</b> was set up in 1989 to join India's separate regional networks into <b>one national grid</b>, and grew into one of the largest transmission systems on Earth — the highways every power maker must use."),
   TL([("1989","India creates one company to carry power across the whole country."),
       ("Over decades","Separate regional networks are stitched into a single national grid."),
       ("Today","Nearly every unit of power that crosses the country rides its highways."),
       ("Tomorrow","New lines reach out to distant sun and wind farms. ⚡")]),
   NOTE("Charlotte's Secret Notebook","Power Grid (1989) joined India's separate networks into ONE national grid and became one of the biggest power-highway builders in the world. Everyone's power rides its roads. 🏆"),
 ]),
 ("c9","CHAPTER 9","The Castle on the Wires","pages 71-80",[
   P("pg_c9_castle","Two kind old men appeared with a glow. Warren pointed at a castle standing on a web of shining wires. \"What keeps rivals out, Charlotte?\"","Walls! But what kind?"),
   MOAT([("🗼","Wall One: Nobody Builds a Second Set of Towers","Stringing towers across an entire country takes decades, permission over every field and river, and a mountain of money. No rival is going to build a whole SECOND set beside them.",False),
         ("🛣️","Wall Two: Everybody Must Use the Road","Coal, hydro, solar, wind — whoever makes the power still has to send it down these wires. When every maker needs your road, they all pay the toll.",False),
         ("🧠","Wall Three: Steady, Careful Know-How","Balancing a nation's power every second, for decades, without dropping it — that skill is built up slowly and can't be bought in a hurry.",False),
         ("⚠️","The Crack in the Wall","A highway is only as strong as its weakest link. One tower down, one line tripped, and a whole region can dim. It must be watched and mended, always.",True)]),
   P("pg_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 grid giant strong, imagine how it could FAIL — a weak link left unmended, a line built where no power ever flows, or growth so fast it strains the balancing — then carefully avoid each one, and keep the highways strong and busy."),
   P("pg_c9_verdict","Warren nodded. \"It owns the road everyone must travel — a mighty castle, so long as not one link is ever left weak.\"","I SEE the whole picture!"),
   NOTE("Charlotte's Secret Notebook · The Big Secret","Power Grid is hard to copy: nobody builds a SECOND set of towers, EVERY maker must use its road, and its balancing skill took decades. But one weak link can dim a whole region. Charlie's trick: picture how you'd lose (a snapped link, an empty line), then never do it. Invert! 🏰"),
 ]),
 ("c10","CHAPTER 10","The Highways of Light","pages 81-88",[
   P("pg_c10_wake","Charlotte woke in her own bed. The great towers were gone… but the lamp on her desk glowed softly.","Was it real? It FELT real…"),
   P("pg_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 road the light travels. Well done."'),
   P("pg_c10_look","She ran outside at dusk. The quiet wires overhead hummed against the sunset — a highway, busy with light, running right over her street.","The road was above my head the whole time — I just never looked up!"),
   WOW("Next time a lamp glows, you'll know the secret: that power drove a long way to reach you. Pushed high by a transformer so it could travel thin and far, stepped gently down for your home, and balanced every single second along the way. Those are <b>the highways of light.</b> 🗼⚡"),
   NOTE("Charlotte's Secret Notebook · What I Learned","➊ Power sent far LEAKS away as heat — distance is the enemy.<br>➋ Transformers push the voltage very HIGH so it travels thin and far.<br>➌ Substations step it back DOWN, gentle and safe for homes.<br>➍ The grid must balance every second: MAKE = USE.<br>➎ Power Grid owns the highways every maker must use — but Charlie's trick: picture how you'd lose (one weak link dims a region), then never do it. 💛"),
 ]),
]

HOOK=("pg_c1_swirl","EVERY ORDINARY THING HIDES A SECRET.",
 "Charlotte found the road that light takes home. But the compass is twitching again — toward the little glass rectangle in her pocket that somehow talks to people on the other side of the world. Where do the words go when there are no wires at all?",
 "NEXT ADVENTURE · The Invisible Wires →")

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">PUSH IT HIGH TO SEND IT FAR</text>
<g><rect x="60" y="112" width="130" height="90" rx="12" fill="#fff" stroke="#171717" stroke-width="4"/><text x="125" y="102" text-anchor="middle" font-family="Baloo 2" font-size="14" fill="#37414d">POWER STATION</text><text x="125" y="165" text-anchor="middle" font-family="Bangers" font-size="24" fill="#37414d">makes it</text><text x="125" y="235" text-anchor="middle" font-family="Nunito" font-size="13" fill="#555">a slow, fat river of power</text></g>
<g stroke="#c8621f" stroke-width="5" fill="#c8621f"><line x1="200" y1="150" x2="310" y2="150" stroke-dasharray="10 8"/><path d="M306 141 L324 150 L306 159Z"/></g>
<g><circle cx="395" cy="150" r="42" fill="#f6b53f" stroke="#c8621f" stroke-width="4"/><text x="395" y="98" text-anchor="middle" font-family="Baloo 2" font-size="14" fill="#c8621f">TRANSFORMER</text><text x="395" y="157" text-anchor="middle" font-family="Bangers" font-size="20" fill="#c8621f">PUSH!</text><text x="395" y="235" text-anchor="middle" font-family="Nunito" font-size="13" fill="#555">voltage pushed very HIGH</text></g>
<g stroke="#2aa15a" stroke-width="3" fill="#2aa15a"><line x1="440" y1="150" x2="600" y2="150" stroke-dasharray="14 8"/><path d="M596 143 L612 150 L596 157Z"/></g>
<text x="520" y="135" text-anchor="middle" font-family="Baloo 2" font-size="12" fill="#2aa15a">thin &amp; fast</text>
<text x="520" y="182" text-anchor="middle" font-family="Nunito" font-size="12" fill="#555">hardly any heat leaks out</text>
<g><rect x="620" y="112" width="150" height="90" rx="12" fill="#fff" stroke="#171717" stroke-width="4"/><text x="695" y="102" text-anchor="middle" font-family="Baloo 2" font-size="14" fill="#2aa15a">YOUR HOME</text><text x="695" y="165" text-anchor="middle" font-family="Bangers" font-size="22" fill="#2aa15a">stepped down</text><text x="695" y="235" text-anchor="middle" font-family="Nunito" font-size="13" fill="#555">gentle and safe for a lamp</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">Power sent far leaks away as HEAT &#8594; so a transformer pushes the voltage HIGH &#8594; it travels thin and far &#8594; then it is stepped DOWN for homes.</text>
<text x="410" y="343" text-anchor="middle" font-family="Nunito" font-size="13" fill="#555">And every second, the power made must exactly match the power used.</text>
</svg><div class="figcap">A transformer pushes the voltage high so power travels far without heating the wire, then steps it back down for homes.</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_miles"); 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/powergrid/_head.html").read()
    tail=open("/root/omahaindia.com/comics/site/book/powergrid/_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()
