#!/usr/bin/env python3
# Book 36 (ONGC) — THE TREASURE BENEATH THE SEA. Science->business: oil & gas is BURIED
# ANCIENT SEA LIFE (tiny sea creatures drank the sun -> sank -> pressed by heat & rock into oil and gas ->
# trapped under a dome of hard rock -> we send sound waves down and read the echoes to MAP it, then drill)
# -> the giant that finds and lifts the treasure that moves India.
import os
ART="/root/omahaindia.com/comics/site/book/ongc/art"
OUT="/root/omahaindia.com/comics/site/book/ongc/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"
CLIFF=("Cliff, a warm friendly Western OFFSHORE GEOLOGIST, NOT Indian, sturdy build, rugged weathered face, "
"hearty smile, bright orange survival suit, a white safety helmet, holding a cylindrical rock core sample 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,3600,f"{STYLE}. BOOK COVER, {CHARLOTTE} standing with {CLIFF} on the deck of a vast offshore oil platform in the open sea, holding up a glowing glass vial of golden-dark oil that shimmers from within like a trapped sunset, deep blue waves and a warm setting sun on the horizon, wonder, cinematic","charlotte"),
 "_ref_cliff":(1024,1024,3601,f"{STYLE}. clean friendly character portrait, {CLIFF}, plain soft warm background, hearty smile, head and shoulders",None),
 # Ch1
 "on_c1_coin":(1024,720,3610,f"{STYLE}. {CHARLOTTE} at home, Grandpa Ben's glowing brass compass twitching between a little glass vial of dark oil and the bright blue flame of a kitchen stove on the table, EXPRESSION puzzled and intrigued, cozy lamp light","charlotte"),
 "on_c1_diary":(1024,720,3611,f"{STYLE}. an open magical diary glowing warm gold on a desk, a faint ribbon of blue-gold light rising from the page and curling into a single shining drop of dark oil, no people",None),
 "on_c1_swirl":(1024,720,3612,f"{STYLE}. {CHARLOTTE} pulled into a swirling spiral of blue and gold light and sea spray from a glowing diary, EXPRESSION thrilled, magical","charlotte"),
 # Ch2 — arrive at the offshore rig, meet Cliff
 "on_c2_arrive":(1024,720,3613,f"{STYLE}. {CHARLOTTE} landing wide-eyed on the steel deck of an enormous offshore oil platform in the middle of the open ocean, blue water to every horizon, EXPRESSION awe and delight, bright daylight","charlotte"),
 "on_c2_cliff":(1024,720,3614,f"{STYLE}. {CLIFF} warmly welcoming {CHARLOTTE} on the platform, tipping his white helmet, EXPRESSION Charlotte shy happy smile; keep the SAME offshore geologist from the reference, same orange survival suit and white helmet and rock core sample","cliff"),
 "on_c2_pit":(1024,720,3615,f"{STYLE}. a vast offshore oil platform seen from the deck, its huge steel legs plunging down through deep blue water toward the dark rock of the sea floor far below, powerful and awe-inspiring, no faces close up",None),
 # Ch3 — the buried sunlight: tiny sea creatures that drank the sun
 "on_c3_leaf":(1024,720,3616,f"{STYLE}. {CLIFF} kneeling to show {CHARLOTTE} a single glowing drop of seawater full of tiny sparkling sea creatures catching a warm sunbeam, EXPRESSION Charlotte fascinated leaning in; SAME offshore geologist, orange suit, white helmet, core sample","cliff"),
 "on_c3_forest":(1024,720,3617,f"{STYLE}. a warm ancient prehistoric sea teeming with countless tiny glowing plankton and little sea creatures drinking bright golden sunlight near the sparkling surface, magical and alive, no people",None),
 "on_c3_store":(1024,720,3618,f"{STYLE}. a friendly close up of tiny sea creatures glowing softly as they each store a little bead of golden sunlight inside themselves like a battery, playful science, no people",None),
 # Ch4 — sank, buried, pressed into oil & gas trapped under a dome
 "on_c4_sink":(1024,720,3619,f"{STYLE}. {CHARLOTTE} watching in wonder as countless tiny sea creatures drift gently down and settle on the dark sea floor, mud slowly burying them layer by layer, EXPRESSION amazed and thoughtful, dim underwater dusk light","charlotte"),
 "on_c4_press":(1024,720,3620,f"{STYLE}. a magical cutaway of the sea floor, many heavy layers of mud and rock pressing down over ages onto buried sea creatures deep below, arrows of pressure, warm underground glow, no people",None),
 "on_c4_rock":(1024,720,3621,f"{STYLE}. a beautiful cutaway close up of golden droplets of oil and shining bubbles of gas gathered in the pores of rock, all caught beneath a smooth dome of hard grey rock like a lid, dark rim bright center, no people",None),
 # Ch5 — we cannot see underground: send sound waves down, read the echoes to MAP it
 "on_c5_burn":(1024,720,3622,f"{STYLE}. a survey ship on the blue sea sending rings of sound waves booming straight down into the sea floor, ripples of sound travelling deep and echoes bouncing back up, magical acoustic glow, no people",None),
 "on_c5_boil":(1024,720,3623,f"{STYLE}. {CLIFF} showing {CHARLOTTE} a glowing map drawn from the echoes, revealing a hidden dome full of oil deep beneath the sea floor, EXPRESSION Charlotte delighted 'aha'; SAME offshore geologist, orange suit, white helmet, core sample","cliff"),
 # Ch6 — drill down and lift the treasure
 "on_c6_spin":(1024,720,3624,f"{STYLE}. {CHARLOTTE} watching a giant drill on the platform spin down through the sea floor toward the hidden dome, her ponytails blown back by the rushing air, EXPRESSION awed and excited, bright rig","charlotte"),
 "on_c6_electric":(1024,720,3625,f"{STYLE}. dark golden oil and clear bright gas rushing up a steel pipe from deep below the sea floor to a glowing offshore platform, the treasure lifted at last into the light, magical, no people",None),
 # Ch7 — the treasure moves the world
 "on_c7_everyone":(1024,720,3626,f"{STYLE}. a joyful scene of cars, trucks, buses, ships, a soaring airplane and a kitchen stove with a cheerful blue flame — all moving and glowing with energy, warm togetherness, no faces close up",None),
 "on_c7_half":(1024,720,3627,f"{STYLE}. a warm storybook map of India alive with moving cars, trains, planes and glowing kitchen flames, streams of fuel flowing to them from a distant offshore oil platform, gentle and grand, no people",None),
 # Ch8 — reveal ONGC
 "on_c8_reveal":(1024,720,3628,f"{STYLE}. {CHARLOTTE} and {CLIFF} standing proudly before a vast field of offshore platforms and a shoreline refinery glowing against a blue sky, EXPRESSION proud recognition; SAME offshore geologist, orange suit, white helmet, core sample","charlotte"),
 "on_c8_1975":(1024,720,3629,f"{STYLE}. warm sepia 1950s scene, India's first oil explorers setting out with old drilling rigs and maps to find the country's very own oil, hopeful workers, inspiring, no text",None),
 "on_c8_scale":(1024,720,3630,f"{STYLE}. a mighty modern offshore oil field at golden hour, many platforms and supply ships spread across a shining sea, the biggest finder of oil and gas in India, proud and grand, no people",None),
 # Ch10 (ch9 uses ritual castle/invert/verdict; ch10 uses ritual wake/diary)
 "on_c10_look":(1024,720,3631,f"{STYLE}. {CHARLOTTE} outside looking with wonder as a car rolls past, a plane crosses the sky and a neighbour's blue stove flame glows — knowing each one holds ancient sea treasure, 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 Drop That Glowed","pages 1-8",[
   P("on_c1_coin","Back home, Grandpa Ben's compass twitched again — pointing between a little vial of dark oil and the bright blue flame of the kitchen stove.","A drop of oil… and a flame? What's the link?",None,"twitch"),
   P("on_c1_diary","The old diary fell open. A new line shimmered in Grandpa Ben's hand.",None,'"Find the treasure the ancient sea left sleeping beneath the waves."'),
   WOW("A dark, oily drop and a dancing flame don't seem to belong together — yet fill a car, fly a plane, light a stove, and it all begins with drops just like this one, pulled up from far beneath the sea. What treasure is hiding in a drop of oil? That's the puzzle of this whole adventure."),
   P("on_c1_swirl","Blue-gold light swirled up like a wave and pulled Charlotte in.","Here we GO!",None,"WHOOSH","#1f6f8c"),
   NOTE("Charlotte's Secret Notebook","Two BIG questions:<br>➊ How can a dark drop of oil move a car and light a flame?<br>➋ Grandpa Ben says it's <i>treasure</i> from the ancient sea. How does treasure get UNDER the sea? 🌊"),
 ]),
 ("c2","CHAPTER 2","The Rig in the Middle of the Sea","pages 9-16",[
   P("on_c2_arrive","One blink, and she stood on a huge steel platform in the middle of the open sea — nothing but blue water to every horizon.","A whole steel island — out in the OCEAN!"),
   P("on_c2_cliff","A cheerful man in an orange suit and white helmet waved. \"I'm Cliff, a rock scientist. Out here we hunt for a very old kind of treasure.\"","Old… TREASURE?!"),
   P("on_c2_pit","He pointed straight down — past the deck, past the waves, to the dark rock far below the sea floor.","The treasure's under the sea <i>and</i> under the rock?","Stick with me, kiddo."),
   NOTE("Charlotte's Secret Notebook","Cliff is a rock scientist (a geologist), and he grins like he has a secret — just like the other guides did. He calls oil 'old treasure'. Okay Cliff… show me how! ✨"),
 ]),
 ("c3","CHAPTER 3","The Tiny Creatures That Drank the Sun","pages 17-26",[
   P("on_c3_leaf","Cliff held a drop of seawater to the light. \"See these specks? Tiny sea creatures. Each one is a little sun-catcher — it drinks sunlight and tucks the energy away inside.\"","Even sea specks store sunlight — like a battery!"),
   P("on_c3_forest","\"Long, long ago — before there were even people — the warm seas were full of them, drinking the sun for millions and millions of years.\"","A whole ocean of tiny sun-catchers!"),
   P("on_c3_store","\"When those little creatures died, all that captured sunshine was still locked inside them, drifting down into the deep.\"","The sunlight didn't leave — it sank!",None,"glow","#1f6f8c"),
   WOW("Here's the first secret! 💡 Tiny sea creatures are living <b>sun-catchers</b>: sunlight goes in, and its energy is stored inside them. The ancient seas were full of them for <b>millions of years</b>. When they died, that old sunlight sank with them into the deep — it didn't disappear."),
   ("diagram",),
   NOTE("Charlotte's Secret Notebook","Tiny sea creatures catch sunlight and store its energy inside. The ancient seas did this for millions of years. When the creatures died, all that captured sunshine sank into the deep, still trapped inside them. ☀️🌊"),
 ]),
 ("c4","CHAPTER 4","Buried Beneath the Sea","pages 27-36",[
   P("on_c4_sink","\"Down they drifted,\" said Cliff, \"settling on the sea floor, buried under mud, layer after layer, deeper and deeper.\"","Down and down, out of sight!"),
   P("on_c4_press","\"For millions of years, heavy rock and mud pressed down on them — squeeze, squeeze, squeeze — hotter and harder.\"","Squished for AGES!",None,"press","#37414d"),
   P("on_c4_rock","\"And slowly, all those squashed little creatures turned into oil and gas — and it gathered in the rock, trapped under a dome of hard stone like a lid.\"","So oil is ancient sea life, turned to treasure!"),
   WOW("Bury the tiny sea creatures deep under mud, press them with heavy rock for <b>millions of years</b>, add heat, and they slowly turn into <b>oil and gas</b>. It seeps up through the rock until a <b>dome of hard stone</b> traps it like a lid — a hidden treasure chest under the sea."),
   NOTE("Charlotte's Secret Notebook · SOLVED (part 1)","Tiny sea creatures were buried, then pressed for millions of years into OIL and GAS. It floats up and gets trapped under a dome of hard rock. Oil = ancient sunlight from the sea! 🛢️"),
 ]),
 ("c5","CHAPTER 5","Reading the Echoes","pages 37-44",[
   P("on_c5_burn","\"But here's the puzzle,\" said Cliff. \"The treasure is buried where no eye can see. So a ship booms sound waves down into the seabed.\"","We can't SEE it — so we listen?",None,"BOOM","#1f6f8c"),
   P("on_c5_boil","\"The sound bounces back, and from those echoes we draw a map — and there it is: a hidden dome full of oil.\"","The echoes DREW a map of the deep!"),
   WOW("You can't see through rock — so we use <b>sound</b>. A ship booms sound waves down; they echo off the buried layers and bounce back. From those echoes, scientists <b>draw a map</b> of what's hidden below and spot the domes where oil and gas are trapped. We map what we cannot see."),
   NOTE("Charlotte's Secret Notebook","We can't see underground, so a ship sends SOUND WAVES down and reads the ECHOES that bounce back. From them we MAP the hidden rock and find the domes of trapped oil. Listen, then look! 🔊🗺️"),
 ]),
 ("c6","CHAPTER 6","The Great Drill","pages 45-52",[
   P("on_c6_spin","With the map in hand, a giant drill roared to life, spinning down through the sea floor toward the hidden dome. Charlotte's ponytails flew back.","The drill is going ALL the way down!"),
   P("on_c6_electric","\"When it breaks into the dome,\" said Cliff, \"the treasure rushes up the pipe — dark oil and clear gas, lifted at last into the light.\"","So THAT'S how you lift it up!"),
   WOW("Once the map shows where to dig, a <b>giant drill</b> bores down through water and rock to the trapped dome. Then the oil and gas <b>rush up the pipe</b> to the platform. Sun → sea creatures → buried → pressed → oil → map → drill → lift. What a journey!"),
   NOTE("Charlotte's Secret Notebook · SOLVED!","A giant drill bores down to the dome; the oil and gas rush up the pipe. The whole chain: SUN → sea creatures → buried &amp; pressed → OIL &amp; GAS → mapped by sound → DRILLED → lifted up! ⛏️🛢️"),
 ]),
 ("c7","CHAPTER 7","The Fuel That Moves the World","pages 53-60",[
   P("on_c7_everyone","Cliff swept his arm across the world. Cars, trucks, buses, ships, a soaring plane, a kitchen's blue flame — all moving on the treasure.","EVERYTHING runs on this?!"),
   P("on_c7_half","\"This treasure,\" said Cliff, \"moves the cars and trucks, flies the planes, cooks the food, and even becomes the plastic in your toys.\"","The whole world runs on ancient seas!"),
   WOW("This isn't a small thing. Oil and gas <b>move almost everything</b> — cars, trucks, ships, planes, the gas that cooks dinner, even the plastic in your toys. A huge part of the world runs on the treasure of ancient seas, lifted from far beneath the waves."),
   NOTE("Charlotte's Secret Notebook","Oil and gas move cars, trucks, ships and planes, cook our food, and even become plastic. So much of the world runs on ancient sea treasure, pulled up from deep beneath the sea. 🚗✈️🔥"),
 ]),
 ("c8","CHAPTER 8 · THE BIG DISCOVERY","The Giant That Finds the Treasure","pages 61-70",[
   P("on_c8_reveal","Cliff led Charlotte to the rail, overlooking the vast field of platforms and a refinery glowing on the shore.","Who FINDS all of this?"),
   P("on_c8_1975","\"In 1956,\" said Cliff, \"India set out to find its very own oil and gas, so it wouldn't have to buy it all from far away.\"","India went hunting for its own treasure!"),
   P("on_c8_scale","\"It searched the land, then the sea — and struck a giant field far out in the ocean, growing into India's greatest treasure-finder.\"","The biggest treasure-hunter in the country!"),
   WOW("A \"company\" can be a giant shared job. <b>ONGC</b> — Oil and Natural Gas Corporation — set out in 1956 to find India's own oil and gas. It struck a mighty field far out at sea and grew into the <b>largest finder of oil and gas in India</b>, lifting the treasure that moves the nation."),
   TL([("1956","India sets out to find its very own oil and gas."),
       ("At sea","It strikes a giant oil field far out in the ocean."),
       ("Today","It is India's largest finder of oil and gas."),
       ("Tomorrow","It begins learning cleaner power too — sun, wind and green fuels. 🌱")]),
   NOTE("Charlotte's Secret Notebook","ONGC (1956) set out to find India's own oil and gas, struck a giant field far out at sea, and became the country's biggest treasure-finder — lifting the fuel that moves the nation. 🏆"),
 ]),
 ("c9","CHAPTER 9","The Castle Beneath the Waves","pages 71-80",[
   P("on_c9_castle","Two kind old men appeared with a glow. Warren pointed at a castle standing on a shining sea of oil rigs. \"What keeps rivals out, Charlotte?\"","Walls! But what kind?"),
   MOAT([("🛢️","Wall One: It Owns the Treasure Fields","The oil and gas lie in fields ONGC found and holds. You cannot lift oil where you don't have a field — and it holds the biggest ones in India.",False),
         ("🌊","Wall Two: The Skill to Drill at Sea","Drilling far out in deep water is fiendishly hard. Rigs, ships and know-how built over decades — a rival can't copy that overnight.",False),
         ("🚗","Wall Three: Woven Into Everything","When a nation's cars, planes, factories and kitchens lean on your fuel, you're very hard to replace quickly.",False),
         ("⚠️","The Crack in the Wall","But YOU don't set the price — the whole WORLD does, and it can rise and fall far away. And the world is slowly turning to cleaner energy. A company tied to ONE treasure must learn new tricks.",True)]),
   P("on_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 an oil giant strong, imagine how it could FADE — the world's price crashing against it, or clinging to one fuel while the world changes — then carefully guard against each one, and start learning clean energy early."),
   P("on_c9_verdict","Warren nodded. \"It owns the fields and the rare skill to drill at sea — a mighty castle, so long as it rides the world's prices and learns cleaner energy too.\"","I SEE the whole picture!"),
   NOTE("Charlotte's Secret Notebook · The Big Secret","ONGC is hard to copy: it OWNS the fields and has the rare SKILL to drill at sea, and the country leans on its fuel. But the WORLD sets the price, and energy is turning cleaner — so it must ADAPT. Charlie's trick: picture how you'd lose (one fuel, wild prices), then never do it. Invert! 🏰"),
 ]),
 ("c10","CHAPTER 10","The Treasure All Around Us","pages 81-88",[
   P("on_c10_wake","Charlotte woke in her own bed. The great platform was gone… but the little vial of oil on her desk shimmered softly.","Was it real? It FELT real…"),
   P("on_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 treasure the ancient sea left us. Well done."'),
   P("on_c10_look","She ran outside. Every passing car, every plane overhead, the blue flame of a neighbour's stove — all of it, quietly, was ancient sea life waking up.","It was buried treasure the whole time — I just couldn't see it!"),
   WOW("Next time a car rolls by or a stove clicks alight, you'll know the secret: it may be <b>treasure from an ancient sea</b>. Tiny creatures drank the sun, sank and were pressed into oil and gas, trapped under a dome of rock — until we mapped it with sound and lifted it into the light. That's <b>the treasure beneath the sea.</b> 🌊🛢️"),
   NOTE("Charlotte's Secret Notebook · What I Learned","➊ Tiny sea creatures are sun-catchers; the ancient seas stored sunlight for millions of years.<br>➋ Buried and pressed, they turned into OIL and GAS, trapped under a dome of rock.<br>➌ We can't see underground, so we send SOUND WAVES down and map the echoes, then DRILL and lift the treasure.<br>➍ It moves the world's cars, planes, ships and stoves.<br>➎ ONGC finds it at giant scale; but Charlie's trick — picture how you'd lose (one fuel, world prices), then adapt to cleaner energy. 💛"),
 ]),
]

HOOK=("on_c1_swirl","EVERY ORDINARY THING HIDES A SECRET.",
 "Charlotte found the treasure the ancient sea left behind. But the compass is twitching again — toward the shining steel of a great bridge, a railway line, a soaring tower. Where does all that mighty metal come from, and who pulls it from the earth?",
 "NEXT ADVENTURE · The Metal That Builds a Nation →")

DIAGRAM='''<div class="panel wide" style="background:#eef6fb;">
<svg viewBox="0 0 820 380"><rect width="820" height="380" fill="#eef6fb"/>
<text x="410" y="38" text-anchor="middle" font-family="Bangers" font-size="24" fill="#1f6f8c">OIL IS TREASURE FROM THE ANCIENT SEA</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 SUN</text><text x="120" y="235" text-anchor="middle" font-family="Nunito" font-size="13" fill="#555">sunlight shines down</text></g>
<g stroke="#1f6f8c" stroke-width="5" fill="#1f6f8c"><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="13" fill="#1f6f8c">ANCIENT SEA</text><text x="395" y="165" text-anchor="middle" font-family="Bangers" font-size="24" fill="#1f6f8c">stores it</text><text x="395" y="235" text-anchor="middle" font-family="Nunito" font-size="13" fill="#555">tiny creatures catch the sun</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">buried &amp; pressed</text>
<text x="540" y="182" text-anchor="middle" font-family="Nunito" font-size="12" fill="#555">for millions of years</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="15" fill="#f6b53f">OIL &amp; GAS</text><text x="695" y="165" text-anchor="middle" font-family="Bangers" font-size="22" fill="#f6b53f">buried treasure</text><text x="695" y="235" text-anchor="middle" font-family="Nunito" font-size="13" fill="#555">trapped under a dome of rock</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">Send SOUND WAVES down &#8594; read the echoes to MAP the hidden dome &#8594; DRILL &#8594; lift the OIL &amp; GAS.</text>
<text x="410" y="343" text-anchor="middle" font-family="Nunito" font-size="13" fill="#555">The sunshine tiny sea creatures caught long ago finally moves your world today.</text>
</svg><div class="figcap">Sunlight is caught by tiny sea creatures, buried and pressed into oil and gas, mapped with sound, then drilled and lifted to move the world.</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_cliff"); 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/ongc/_head.html").read()
    tail=open("/root/omahaindia.com/comics/site/book/ongc/_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()
