#!/usr/bin/env python3
# Book 50 (Adani Enterprises) — THE SEED THAT GROWS COMPANIES. Science->business: a NURSERY-INCUBATOR
# (raise a seed under shelter -> grow the seedling with care -> plant it out to face the weather itself ->
# it stands alone as its own tree) -> the giant that STARTS new businesses, grows them, then lets them stand
# alone (ports, energy). FINALE BOOK: also closes Charlotte's whole journey — the diary, Ben's margin of
# safety, Warren & Charlie's moats, and that she can now read any business herself.
import os
ART="/root/omahaindia.com/comics/site/book/adanient/art"
OUT="/root/omahaindia.com/comics/site/book/adanient/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"
ORIN=("Orin, a warm friendly Western nursery GARDENER and plant-raiser, NOT Indian, sun-weathered face, "
"wise encouraging smile, a green gardening apron with pockets, cradling a little seedling in a terracotta pot")

# name -> (w,h,seed,prompt,ref). ref set -> Seedream character; None -> flux scene. Ritual panels copied by mkbook.
NEW={
 "00_cover":(1024,1180,5000,f"{STYLE}. BOOK COVER, {CHARLOTTE} standing with {ORIN} in a sunlit nursery garden, holding up a tiny green seedling in a pot that glows warmly from within, behind them the same seedling rises into a mighty grown tree whose branches turn into a busy port and a glowing power plant, wonder, cinematic","charlotte"),
 "_ref_orin":(1024,1024,5001,f"{STYLE}. clean friendly character portrait, {ORIN}, plain soft warm background, kind encouraging smile, head and shoulders",None),
 # Ch1
 "ae_c1_coin":(1024,720,5010,f"{STYLE}. {CHARLOTTE} at home, Grandpa Ben's glowing brass compass twitching between a single tiny seed and a tall glowing grown tree on the table, EXPRESSION puzzled and intrigued, cozy lamp light","charlotte"),
 "ae_c1_diary":(1024,720,5011,f"{STYLE}. an open magical diary glowing warm gold on a desk, a faint green shoot rising from the page and curling up into a tiny glowing tree, no people",None),
 "ae_c1_swirl":(1024,720,5012,f"{STYLE}. {CHARLOTTE} pulled into a swirling spiral of golden-green light and floating seeds and leaves from a glowing diary, EXPRESSION thrilled, magical","charlotte"),
 # Ch2 — arrive at the great nursery, meet Orin
 "ae_c2_arrive":(1024,720,5013,f"{STYLE}. {CHARLOTTE} landing wide-eyed at the edge of an enormous sunlit nursery garden, endless rows of little potted seedlings and rows of glass greenhouses stretching to the horizon, EXPRESSION awe and delight, bright morning light","charlotte"),
 "ae_c2_orin":(1024,720,5014,f"{STYLE}. {ORIN} warmly welcoming {CHARLOTTE} in the nursery, holding out a seedling in a terracotta pot, EXPRESSION Charlotte shy happy smile; keep the SAME gardener from the reference, same green apron, same seedling pot","orin"),
 "ae_c2_pit":(1024,720,5015,f"{STYLE}. a vast nursery seen from above, thousands of young trees in neat rows of pots and long glass greenhouses, tiny gardeners with watering cans for scale, gentle and awe-inspiring, no faces close up",None),
 # Ch3 — a seed needs shelter first
 "ae_c3_leaf":(1024,720,5016,f"{STYLE}. {ORIN} kneeling to show {CHARLOTTE} a single tiny seed resting in his open palm, a soft golden glow of life hidden inside it, EXPRESSION Charlotte fascinated leaning in; SAME gardener, green apron, seedling pot","orin"),
 "ae_c3_forest":(1024,720,5017,f"{STYLE}. the warm inside of a big glass greenhouse full of tender little seedlings in pots, soft misty light, sheltered from wind and rain, cosy and alive, no people",None),
 "ae_c3_store":(1024,720,5018,f"{STYLE}. a friendly close up of a single seed cracking open in dark soil, a first white root reaching down and a first green shoot curling up toward the light, playful science, no people",None),
 # Ch4 — grown under care in the greenhouse
 "ae_c4_sink":(1024,720,5019,f"{STYLE}. {CHARLOTTE} watching in wonder as gentle hands tuck a tiny seedling into a warm pot of rich soil inside the greenhouse, kept safe and snug, EXPRESSION tender and curious, soft green light","charlotte"),
 "ae_c4_press":(1024,720,5020,f"{STYLE}. a magical cheerful scene of a young sapling in a greenhouse being cared for — a watering can raining gentle drops, a little wooden stake tied to hold it straight, warm sun lamps above, no people",None),
 "ae_c4_rock":(1024,720,5021,f"{STYLE}. a beautiful close up of a strong healthy young sapling in a pot, glossy leaves and a sturdy little trunk, thick roots filling the pot, ready and full of life, warm glow, no people",None),
 # Ch5 — out into the weather: planting it out to stand on its own
 "ae_c5_burn":(1024,720,5022,f"{STYLE}. a young sapling being planted out of its pot into open ground on a green hillside, its roots spreading into the wide earth for the first time, hopeful and brave, warm golden light, no people",None),
 "ae_c5_boil":(1024,720,5023,f"{STYLE}. {ORIN} showing {CHARLOTTE} how the newly planted young tree now stands out in the open facing wind and rain and sun all by itself, bending but holding firm, EXPRESSION Charlotte thoughtful 'aha'; SAME gardener, green apron","orin"),
 # Ch6 — it stands alone as its own tree (ports, energy)
 "ae_c6_spin":(1024,720,5024,f"{STYLE}. {CHARLOTTE} looking up in wonder as the little planted tree has grown into a tall mighty tree standing proudly on its own, birds nesting in its branches, EXPRESSION awed and excited, bright sky","charlotte"),
 "ae_c6_electric":(1024,720,5025,f"{STYLE}. a magical scene where several grown trees each turn into a different thriving business — one tree becomes a busy seaside port with ships and cranes, another becomes a glowing power plant, another a solar and wind farm, each standing on its own, no faces close up",None),
 # Ch7 — a whole forest from one nursery
 "ae_c7_everyone":(1024,720,5026,f"{STYLE}. a joyful wide orchard-forest of many different grown trees, each one a different thriving business, all sprung from the same nursery, warm togetherness, no faces close up",None),
 "ae_c7_half":(1024,720,5027,f"{STYLE}. a warm storybook map of India dotted with many grown trees spreading from a single glowing nursery — ports on the coast, power plants inland, roads and farms — gentle and grand, no people",None),
 # Ch8 — reveal Adani Enterprises
 "ae_c8_reveal":(1024,720,5028,f"{STYLE}. {CHARLOTTE} and {ORIN} standing proudly before a great nursery-company where seedlings on one side grow into towering business-trees on the other, glowing against a blue sky, EXPRESSION proud recognition; SAME gardener, green apron","charlotte"),
 "ae_c8_1975":(1024,720,5029,f"{STYLE}. warm sepia 1980s scene, a small hopeful trading shop with a single tiny sapling on the counter, the very first seed of what would become a giant, inspiring, no text",None),
 "ae_c8_scale":(1024,720,5030,f"{STYLE}. a mighty modern nursery-incubator at golden hour, glass greenhouses on one side and colossal grown business-trees — ports, power, energy — on the other, the giant that raises new companies, proud and grand, no people",None),
 # Ch10 (ch9 uses ritual castle/invert/verdict; ch10 uses ritual wake/diary)
 "ae_c10_look":(1024,720,5031,f"{STYLE}. {CHARLOTTE} standing in a bright field at dawn looking around with knowing wonder as ports, power plants, roads and trees rise all around her, each one once a tiny seed, EXPRESSION delighted wonder and quiet confidence","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 Seed and the Grown Tree","pages 1-8",[
   P("ae_c1_coin","Back home, Grandpa Ben's compass twitched again — pointing between a single tiny seed and a tall glowing tree.","A little seed… and a mighty tree? What's the link?",None,"twitch"),
   P("ae_c1_diary","The old diary fell open. A new line shimmered in Grandpa Ben's hand.",None,'"Find where new trees are born — and learn to read any of them yourself."'),
   WOW("A seed is so small you could lose it in your pocket, yet inside it sleeps a whole tree — branches, fruit, a lifetime of shade. How does a tiny seed become a giant? And could a COMPANY grow the very same way? That's the puzzle of this last adventure."),
   P("ae_c1_swirl","Golden-green light swirled up and pulled Charlotte in.","One more time — here we GO!",None,"WHOOSH","#2aa15a"),
   NOTE("Charlotte's Secret Notebook","Two BIG questions:<br>➊ How does a tiny seed grow into a mighty tree?<br>➋ Grandpa Ben says I can now <i>read any business myself</i>. Is a company really just a seed that grows? 🌱"),
 ]),
 ("c2","CHAPTER 2","The Garden Where Trees Are Born","pages 9-16",[
   P("ae_c2_arrive","One blink, and she stood at the edge of the biggest garden she'd ever seen — endless rows of tiny pots and rows of shining greenhouses.","It's a whole factory for growing TREES!"),
   P("ae_c2_orin","A kind man in a green apron waved a seedling. \"I'm Orin, a plant-raiser. Here we start new trees from seeds and grow them up strong.\"","You GROW trees on purpose?!"),
   P("ae_c2_pit","Far off, thousands of little green seedlings stood in neat rows, more than she could count.","So many baby trees — where do they all GO?","Stick with me, kiddo."),
   NOTE("Charlotte's Secret Notebook","Orin is a plant-raiser (a nurseryman), and he grins like he has a secret — just like every guide before him. He calls this place a 'nursery'. Okay Orin… show me how a seed grows up! ✨"),
 ]),
 ("c3","CHAPTER 3","A Seed Needs Shelter First","pages 17-26",[
   P("ae_c3_leaf","Orin cupped a single seed. \"Every big tree begins this small. But a seed is tender — the wind and rain would flatten it. So first, we keep it safe.\"","Such a tiny thing… inside is a whole tree?"),
   P("ae_c3_forest","\"In here,\" he said, \"under warm glass, out of the storm, a seed can sprout in peace. Shelter first — that's the rule.\"","A cosy little house for baby trees!"),
   P("ae_c3_store","\"Warm and safe, the seed cracks open — a root reaches down, a shoot reaches up. It has begun.\"","It's WAKING UP!",None,"sprout","#2aa15a"),
   WOW("Here's the first secret! 🌱 A seed is full of promise but far too tender for the open world. So a nursery gives it <b>shelter first</b> — warm soil, gentle water, out of the wind — a safe place to sprout. A new tree, like a new business, needs protection before it can stand."),
   ("diagram",),
   NOTE("Charlotte's Secret Notebook","A seed holds a whole tree inside it, but it's fragile. First it needs SHELTER — warmth, water, safety — so it can sprout without being flattened. New things must be protected while they're small. 🌱🏠"),
 ]),
 ("c4","CHAPTER 4","Grown With Care","pages 27-36",[
   P("ae_c4_sink","\"Now we grow it,\" said Orin, tucking the seedling into a warm pot of rich, dark soil.","Snug as a bug — keep it safe!"),
   P("ae_c4_press","\"Water it, feed it, and tie it to a little stake so it grows up straight and true — day after day, season after season.\"","Watered, fed, and held up tall!",None,"drip drip","#2aa15a"),
   P("ae_c4_rock","\"And slowly it becomes a sturdy young sapling, roots full and strong, ready for what comes next.\"","Look how STRONG it got!"),
   WOW("Shelter is only the start. A young tree must be <b>grown with care</b> — watered, fed, and staked up straight — for season after season. A brand-new business is the same: someone must patiently tend it until its roots are strong. Growing takes <b>time and hard work.</b>"),
   NOTE("Charlotte's Secret Notebook · SOLVED (part 1)","A sheltered seedling is grown with care — water, food, and a stake to keep it straight — until it's a strong young sapling. New businesses need patient tending too, not just a lucky start. 🌿"),
 ]),
 ("c5","CHAPTER 5","Out Into the Weather","pages 37-44",[
   P("ae_c5_burn","Then Orin carried the sapling outside and planted it in the open ground. Its roots spread wide into the earth.","Wait — you're taking it OUT of the greenhouse?",None,"dig dig","#c8621f"),
   P("ae_c5_boil","\"A tree can't hide under glass forever,\" he said. \"To grow truly big, it must face the wind and rain and sun on its OWN.\"","It has to stand up for itself now!"),
   WOW("Here's the turn in the tale: a seedling can't stay sheltered forever. To become mighty, it must be <b>planted out</b> — sent into the open to face the weather itself. A grown business must one day <b>stand on its own</b> too, without the nursery holding it up."),
   NOTE("Charlotte's Secret Notebook","A tree that never leaves the greenhouse stays small. To grow big it must be planted OUT and face wind, rain and sun by itself. Shelter first — then stand alone. That's how things grow up. 🌬️🌳"),
 ]),
 ("c6","CHAPTER 6","Standing On Its Own","pages 45-52",[
   P("ae_c6_spin","Seasons turned. The little sapling had become a tall, mighty tree, standing proud in the open with birds in its branches.","It made it — all on its OWN!"),
   P("ae_c6_electric","\"And here's the wonder,\" said Orin. \"One nursery raises MANY trees — and each grows into something different. One becomes a busy port. One becomes a power plant.\"","Whole BUSINESSES, grown like trees!"),
   WOW("Rushing from tiny to towering, each planted tree becomes its <b>own grown thing</b> — a port, a power plant, a solar farm. A nursery starts them, grows them, then lets them stand alone. Seed → shelter → care → planted out → its own mighty tree. What a journey!"),
   NOTE("Charlotte's Secret Notebook · SOLVED!","One nursery raises many seeds into many grown trees — and each stands on its own as a different business: a port, a power plant, a farm. The whole chain: SEED → SHELTER → CARE → PLANTED OUT → ITS OWN TREE! 🌳⚓"),
 ]),
 ("c7","CHAPTER 7","A Whole Forest From One Garden","pages 53-60",[
   P("ae_c7_everyone","Orin swept his arm across the land. A whole orchard-forest of grown trees spread out — every one a different thriving business.","ALL of these came from one little garden?!"),
   P("ae_c7_half","\"Yes,\" said Orin. \"Ports on the coast, power inland, roads and farms — all started here, as seeds no bigger than your thumbnail.\"","A forest of companies, from one nursery!"),
   WOW("This isn't a small thing. From <b>one nursery</b> can spring a whole forest — ports, power plants, solar farms, roads — each a giant that began as a single seed. A company that's good at <b>starting and growing</b> new businesses can raise an entire forest of them."),
   NOTE("Charlotte's Secret Notebook","A single nursery can grow a whole forest of different businesses — ports, power, farms, roads. All from tiny seeds, sheltered and grown and planted out. One garden, many mighty trees. 🌏🌲"),
 ]),
 ("c8","CHAPTER 8 · THE BIG DISCOVERY","The Giant That Grows Companies","pages 61-70",[
   P("ae_c8_reveal","Orin led Charlotte to a viewpoint — seedlings on one side, towering business-trees on the other.","Who runs this amazing nursery?"),
   P("ae_c8_1975","\"It began in 1988,\" said Orin, \"as one small trading shop — a single seed of a company.\"","From ONE little shop?!"),
   P("ae_c8_scale","\"And it learned to do this again and again — start a business, grow it, plant it out — until it became a giant that grows OTHER companies.\"","An incubator — a nursery for BUSINESSES!"),
   WOW("A \"company\" can be a nursery for other companies. <b>Adani Enterprises</b> began in 1988 as a small trading firm, and grew skilled at <b>starting new businesses, raising them, then letting them stand alone</b> — ports and energy among them. That kind of company is called an <b>incubator.</b>"),
   TL([("1988","Adani Enterprises begins as one small trading shop — a single seed."),
       ("Over the years","It learns to start new businesses, grow them, and plant them out on their own."),
       ("Ports & Energy","Some seedlings grow into giant trees — seaports, power, solar and wind — each its own company."),
       ("Today","It keeps sprouting new seeds — the nursery that grows companies. 🌱")]),
   NOTE("Charlotte's Secret Notebook","Adani Enterprises (1988) started as one tiny trading shop and became an INCUBATOR — it starts new businesses, grows them, then lets them stand alone as their own companies, like ports and energy. A nursery for companies! 🏆"),
 ]),
 ("c9","CHAPTER 9","The Castle in the Garden","pages 71-80",[
   P("ae_c9_castle","Two kind old men appeared with a glow. Warren pointed at a castle standing on a green, blossoming nursery hill. \"What keeps rivals out, Charlotte?\"","Walls! But what kind?"),
   MOAT([("🌱","Wall One: Skill at Starting","It knows how to begin a business from almost nothing — to plant a seed where others see only bare ground. That skill is rare and hard to copy.",False),
         ("🌳","Wall Two: Skill at Growing","It knows how to raise a tiny sapling into a giant — ports, power, energy — with patience and know-how built over many years.",False),
         ("🌲","Wall Three: A Whole Orchard","It has grown MANY trees, not one. If a single tree has a bad season, the others stand strong and carry the garden on.",False),
         ("⚠️","The Crack in the Wall","Growing fast on BORROWED money is risky. Pile too much weight on a young tree and it can bend — and a tree bent too far can break. Grow bold, but never too heavy.",True)]),
   P("ae_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 company-grower strong, imagine how it could FALL — borrowing so much that one bad storm snaps a young tree, or planting so fast the roots never take hold — then carefully avoid each one, and grow no faster than the roots can hold."),
   P("ae_c9_verdict","Warren nodded. \"Its moat is the skill of starting and growing — a mighty castle, so long as it never lets its young trees carry more weight than they can bear.\"","I can READ this whole company myself!"),
   NOTE("Charlotte's Secret Notebook · The Big Secret","Adani Enterprises' moat is the SKILL of starting and growing businesses — hard to copy, and it grows a whole orchard, not one tree. But beware: growing fast on borrowed money is risky — a young tree bent by too much weight can break. Charlie's trick: picture how you'd lose (too much debt), then never do it. Invert! 🏰"),
 ]),
 ("c10","CHAPTER 10","Everything Began as a Seed","pages 81-88",[
   P("ae_c10_wake","Charlotte woke in her own bed. The great nursery was gone… but a tiny seed on her desk shimmered softly.","Was it real? It FELT real…"),
   P("ae_c10_diary","On the diary's page, a last line glowed — as if Grandpa Ben wrote it just for her.",None,'"You can read any business now. My work is done. Go gently. — Ben"'),
   P("ae_c10_look","She ran outside at dawn. Ports, power plants, shops, trees — she saw them all with new eyes now, each one once a tiny seed, each one a business she could read.","I can see how ALL of it grows — I finally understand!"),
   WOW("And so Charlotte's whole journey comes together. 💛 Grandpa <b>Ben</b>, who first taught her Warren, gave her the <b>margin of safety</b> — never pay too much, always leave room to be wrong. <b>Warren and Charlie</b> showed her the <b>moat</b> — what keeps a great company safe. And now, from a lump of coal to a seed that grows companies, she can <b>read any business herself.</b> That's <b>the seed that grows companies.</b> 🌱🏰"),
   NOTE("Charlotte's Secret Notebook · What I Learned","➊ A seed is fragile — it needs SHELTER first, then must face the weather on its own.<br>➋ An incubator STARTS new businesses, GROWS them, then lets them stand alone — like ports and energy.<br>➌ Adani Enterprises' moat is the SKILL of starting and growing; its risk is too much borrowed weight.<br>➍ Grandpa Ben's gift: the <i>margin of safety</i> — never overpay, leave room to be wrong.<br>➎ Warren & Charlie's gift: the <i>moat</i>. Now I can read ANY business myself. Thank you, everyone. 💛"),
 ]),
]

HOOK=("ae_c10_look","EVERY GREAT COMPANY BEGAN AS A SEED.",
 "Charlotte set out not knowing how a lamp could glow — and now she can read any business in the world, from the roots up. The diary is quiet at last. But wherever a new seed is planted, a new story is waiting… and now she knows how to read it herself.",
 "THE END · Charlotte's Journey Complete 💛")

DIAGRAM='''<div class="panel wide" style="background:#f0f7ee;">
<svg viewBox="0 0 820 380"><rect width="820" height="380" fill="#f0f7ee"/>
<text x="410" y="38" text-anchor="middle" font-family="Bangers" font-size="24" fill="#2aa15a">A NURSERY GROWS COMPANIES</text>
<g><circle cx="120" cy="150" r="30" fill="#c8a15a" stroke="#7a5a2a" stroke-width="4"/><text x="120" y="112" text-anchor="middle" font-family="Baloo 2" font-size="15" fill="#7a5a2a">THE SEED</text><text x="120" y="235" text-anchor="middle" font-family="Nunito" font-size="13" fill="#555">tiny but full of promise</text></g>
<g stroke="#2aa15a" stroke-width="5" fill="#2aa15a"><line x1="160" y1="150" x2="300" y2="150" stroke-dasharray="10 8"/><path d="M296 141 L314 150 L296 159Z"/></g>
<g><rect x="320" y="112" width="150" height="90" rx="12" fill="#fff" stroke="#171717" stroke-width="4"/><text x="395" y="102" text-anchor="middle" font-family="Baloo 2" font-size="14" fill="#2aa15a">SHELTER &amp; CARE</text><text x="395" y="165" text-anchor="middle" font-family="Bangers" font-size="24" fill="#2aa15a">it sprouts</text><text x="395" y="235" text-anchor="middle" font-family="Nunito" font-size="13" fill="#555">warm, watered, kept safe</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">planted OUT</text>
<text x="540" y="182" text-anchor="middle" font-family="Nunito" font-size="12" fill="#555">to face the weather</text>
<g><rect x="620" y="112" width="150" height="90" rx="12" fill="#2aa15a" stroke="#171717" stroke-width="4"/><text x="695" y="102" text-anchor="middle" font-family="Baloo 2" font-size="16" fill="#c8621f">ITS OWN TREE</text><text x="695" y="165" text-anchor="middle" font-family="Bangers" font-size="20" fill="#fff">a port · a power plant</text><text x="695" y="235" text-anchor="middle" font-family="Nunito" font-size="13" fill="#555">a grown company, standing alone</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">Shelter the seed &#8594; grow it with care &#8594; plant it OUT to stand alone &#8594; it becomes its own mighty tree.</text>
<text x="410" y="343" text-anchor="middle" font-family="Nunito" font-size="13" fill="#555">An incubator does the same with companies — starts them, grows them, then lets them stand on their own.</text>
</svg><div class="figcap">A seed is sheltered, grown with care, then planted out to stand alone — the way an incubator raises new companies.</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_orin"); 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/adanient/_head.html").read()
    tail=open("/root/omahaindia.com/comics/site/book/adanient/_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()
