#!/usr/bin/env python3
# Book 13 (Titan) — TIME ON YOUR WRIST. Science->business: the quartz crystal that vibrates
# exactly the same number of times each second -> a business built on precision & trust (watches, Tanishq gold).
import os
ART="/root/omahaindia.com/comics/site/book/titan/art"
OUT="/root/omahaindia.com/comics/site/book/titan/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"
THEO=("Theo, a warm friendly watchmaker, round jeweller's loupe pushed up on his forehead, a neat apron over a "
"shirt, tidy short beard, gentle patient smile")

NEW={
 "00_cover":(1024,1180,1300,f"{STYLE}. BOOK COVER, {CHARLOTTE} standing with {THEO} beside a giant beautiful glowing wristwatch with sparkling gears and a softly pulsing tiny crystal at its heart, warm elegant light, wonder, cinematic","charlotte"),
 "_ref_theo":(1024,1024,1301,f"{STYLE}. clean friendly character portrait, {THEO}, plain soft warm background, gentle smile, head and shoulders",None),
 # Ch1
 "ti_c1_watch":(1024,720,1310,f"{STYLE}. {CHARLOTTE} at home holding a glowing brass compass that twitches toward a wristwatch ticking on the table, EXPRESSION puzzled and intrigued, cozy lamp light","charlotte"),
 "ti_c1_diary":(1024,720,1311,f"{STYLE}. an open magical diary glowing warm gold, faint ticking clock-hands of light rising from the page, no people",None),
 "ti_c1_swirl":(1024,720,1312,f"{STYLE}. {CHARLOTTE} pulled into a swirling spiral of golden light and floating clock gears from a glowing diary, EXPRESSION thrilled, magical","charlotte"),
 # Ch2
 "ti_c2_arrive":(1024,720,1313,f"{STYLE}. {CHARLOTTE} landing wide-eyed in a cozy warm watchmaker's workshop full of tiny gears, tools and beautiful watches, EXPRESSION awe and delight","charlotte"),
 "ti_c2_theo":(1024,720,1314,f"{STYLE}. {THEO} warmly welcoming {CHARLOTTE} into his watch workshop, EXPRESSION Charlotte shy happy smile; keep the SAME watchmaker from the reference, same loupe and apron","theo"),
 "ti_c2_wall":(1024,720,1315,f"{STYLE}. a beautiful wall of many elegant watches all ticking together, close up, warm light, no people",None),
 # Ch3 — the crystal
 "ti_c3_crystal":(1024,720,1316,f"{STYLE}. {THEO} holding up a tiny glowing crystal with tweezers, it pulses with a gentle spark of light, teaching, EXPRESSION Charlotte fascinated leaning in; SAME watchmaker, loupe and apron","theo"),
 "ti_c3_buzz":(1024,720,1317,f"{STYLE}. a cute magnified crystal buzzing and vibrating super fast with little motion lines and sparks, playful science, no people",None),
 "ti_c3_count":(1024,720,1318,f"{STYLE}. a friendly cartoon showing a tiny crystal vibrating and a happy little counter ticking, when the count fills up one whole second passes, playful, no numbers no text",None),
 # Ch4 — beats to hands
 "ti_c4_chip":(1024,720,1319,f"{STYLE}. a cute tiny glowing chip inside a watch counting the crystal's beats and gently nudging the watch hands forward, science made friendly, no people",None),
 "ti_c4_gears":(1024,720,1320,f"{STYLE}. beautiful shining little gears turning each other inside a watch, moving the hands smoothly, close up, warm, no people",None),
 # Ch5 — precision
 "ti_c5_race":(1024,720,1321,f"{STYLE}. a friendly comparison, an old wobbly clock drifting wrong beside a steady exact watch keeping perfect time, playful, no people, no numbers",None),
 "ti_c5_exact":(1024,720,1322,f"{STYLE}. {CHARLOTTE} realising why exact time matters, an understanding 'aha' look, with a train and a school bell in the warm background; EXPRESSION bright understanding","charlotte"),
 # Ch6 — jewellery
 "ti_c6_gold":(1024,720,1323,f"{STYLE}. {THEO} showing {CHARLOTTE} a gleaming piece of gold jewellery, teaching how to know it is real and pure, EXPRESSION Charlotte curious and admiring; SAME watchmaker","theo"),
 "ti_c6_pure":(1024,720,1324,f"{STYLE}. a friendly comparison of pure bright gold beside dull mixed metal, with a little magic tester glowing on the real one, playful, no people, no text",None),
 # Ch7 — trust
 "ti_c7_shop":(1024,720,1325,f"{STYLE}. a warm bright elegant jewellery-and-watch shop where a happy family is trusted and delighted picking a piece, warm slice of life",None),
 # Ch8 — reveal
 "ti_c8_reveal":(1024,720,1326,f"{STYLE}. {CHARLOTTE} and {THEO} standing proudly before a grand elegant company headquarters glowing warmly, EXPRESSION proud recognition; SAME watchmaker","charlotte"),
 "ti_c8_1984":(1024,720,1327,f"{STYLE}. warm sepia 1980s scene, hopeful people starting a bold new watch company in India with careful craft and modern machines, inspiring, no text",None),
 # Ch10 (ch9 uses ritual)
 "ti_c10_look":(1024,720,1328,f"{STYLE}. {CHARLOTTE} outside looking with wonder at watches on wrists, a clock tower and shining jewellery all around her bright neighbourhood, EXPRESSION delighted wonder, morning","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 Tick That Never Missed","pages 1-8",[
   P("ti_c1_watch","Back home, Grandpa Ben's compass twitched — this time at a little watch, ticking away.","A watch? What's the secret in a TICK?",None,"twitch"),
   P("ti_c1_diary","The diary fell open. A line shimmered in Grandpa Ben's hand.",None,'"Find the tiny heart that beats exactly the same, forever."'),
   WOW("A good watch is never a second wrong, day after day, year after year. What could keep time SO exactly, all on its own? That's the puzzle of this adventure."),
   P("ti_c1_swirl","Golden light and gears swirled up and pulled Charlotte in.","Here we GO!",None,"WHOOSH","#8a5ad6"),
   NOTE("Charlotte's Secret Notebook","Two BIG questions:<br>➊ What inside a watch beats so EXACTLY that it never drifts wrong?<br>➋ Why do people trust a company so much with something precious like gold? ⌚"),
 ]),
 ("c2","CHAPTER 2","The House of Time","pages 9-16",[
   P("ti_c2_arrive","One blink, and she stood in a cozy workshop full of gears, tools and gleaming watches.","It's a whole HOUSE of time!"),
   P("ti_c2_theo","A kind man with a loupe smiled. \"I'm Theo, a watchmaker. I build tiny machines that count time perfectly.\"","You COUNT time?!"),
   P("ti_c2_wall","A whole wall of watches ticked softly together.","They're all keeping the SAME time!","Because they share one tiny secret, kiddo."),
   NOTE("Charlotte's Secret Notebook","Theo builds machines that 'count time.' And he grins like he knows a secret, just like Gus and Mia did. Okay Theo… show me! ✨"),
 ]),
 ("c3","CHAPTER 3","The Crystal That Counts","pages 17-26",[
   P("ti_c3_crystal","Theo held up a tiny crystal. \"THIS is the heart. Give it a little spark of electricity, and it buzzes.\"","A buzzing crystal?"),
   P("ti_c3_buzz","\"But here's the magic: it always buzzes the SAME number of times every second. Exactly. Never more, never less.\"","The same count EVERY time!",None,"bzzz","#8a5ad6"),
   P("ti_c3_count","\"So the watch just COUNTS the buzzes. When it counts a whole heap of them, exactly one second has passed.\"","Counting buzzes… to measure time!"),
   WOW("Here's the secret! ⌚ A tiny <b>quartz crystal</b> vibrates the <b>exact same number of times every second</b> when given a little electricity. The watch counts those buzzes — and counting something perfectly steady is how it keeps perfect time."),
   ("diagram",),
   NOTE("Charlotte's Secret Notebook · SOLVED!","A quartz CRYSTAL buzzes the exact same number of times each second. The watch COUNTS the buzzes — count a full heap and one second has passed. Steady buzz = perfect time. ✅"),
 ]),
 ("c4","CHAPTER 4","From Beats to Hands","pages 27-34",[
   P("ti_c4_chip","\"A tiny chip counts the buzzes,\" said Theo, \"and every second it nudges the hands forward one tick.\"","Count… then tick the hands!"),
   P("ti_c4_gears","\"Little gears pass the movement along, turning the seconds into minutes into hours.\"","Gears sharing the work!",None,"tick","#2aa15a"),
   WOW("The crystal buzzes, a <b>chip counts</b>, and tiny <b>gears</b> turn that counting into the smooth sweep of the hands. Buzz → count → tick. That's the whole machine on your wrist."),
   NOTE("Charlotte's Secret Notebook","A chip counts the crystal's buzzes and nudges the hands one tick each second; gears turn seconds into minutes into hours. Buzz, count, tick! ⚙️"),
 ]),
 ("c5","CHAPTER 5","Why Exact Matters","pages 35-42",[
   P("ti_c5_race","Theo showed two clocks. One drifted wrong; the exact one stayed true.","The wobbly one is already LATE!"),
   P("ti_c5_exact","\"A watch a little wrong each day is soon very wrong,\" said Theo. \"Trains, schools, doctors — they all need EXACT.\"","Being exact really MATTERS!"),
   WOW("A clock that's a tiny bit wrong each day adds up to being very wrong. Trains, hospitals and schools all depend on <b>exact</b> time. Precision isn't fussy — it's what makes a watch worth trusting."),
   NOTE("Charlotte's Secret Notebook","A little wrong each day becomes very wrong. Being EXACT is why a watch is worth trusting — the whole world runs on precise time. ⏱️"),
 ]),
 ("c6","CHAPTER 6","More Than a Watch","pages 43-52",[
   P("ti_c6_gold","\"We make more than watches,\" Theo smiled, holding up gold jewellery. \"But gold has a puzzle: how do you KNOW it's real and pure?\"","Can't you just… see it?"),
   P("ti_c6_pure","\"Not always. Pure gold is soft and bright; cheats mix in dull metal. So we test and promise every piece is exactly as pure as we say.\"","A promise you can TRUST!"),
   WOW("Gold jewellery has a hidden problem: you can't easily tell pure gold from a cheat. So the real magic a jewellery company sells is a <b>promise</b> — tested, guaranteed purity — the same care for exactness as in a watch."),
   NOTE("Charlotte's Secret Notebook","With gold you can't easily see if it's pure — so the company TESTS it and promises exactly how pure it is. Same love of 'exact' as the watches. 💛"),
 ]),
 ("c7","CHAPTER 7","Trust You Can Wear","pages 53-60",[
   P("ti_c7_shop","In a bright elegant shop, a happy family chose a piece, sure it was real and fair.","They TRUST the shop completely!"),
   WOW("When something is precious and you can't check it yourself, you buy from whom you <b>trust</b>. A jewellery-and-watch brand that keeps its promise for years earns a trust rivals can't quickly copy. Trust is the thing you're really wearing."),
   NOTE("Charlotte's Secret Notebook","When you can't check gold yourself, you buy from a brand you TRUST. Years of keeping the promise = trust rivals can't copy fast. 🤝"),
 ]),
 ("c8","CHAPTER 8 · THE BIG DISCOVERY","The Careful Craftsman","pages 61-70",[
   P("ti_c8_reveal","Theo led Charlotte outside. Above the elegant building glowed a name she'd seen on watches and shops.","It's <b>Titan!</b>"),
   P("ti_c8_1984","\"It began in 1984,\" said Theo, \"choosing to make watches of real quality when few in India did — then careful, trusted gold jewellery too.\"","Quality first — from the start!"),
   WOW("A \"company\" is a long chain of <b>careful choices.</b> Titan started in 1984 making quality watches, then brought the same exactness and trust to gold jewellery. Precision plus a promise kept for decades made it India's most trusted watch and jewellery maker."),
   TL([("1984","A bold new company starts making quality Indian watches."),
       ("1990s","It grows trusted watch brands loved across India."),
       ("1990s-2000s","It brings tested, guaranteed-pure gold jewellery to families."),
       ("Today","One of India's most trusted watch & jewellery makers. ⌚")]),
   NOTE("Charlotte's Secret Notebook","Titan (1984) chose QUALITY first — great watches, then trusted gold. Same care for 'exact' in both. Careful + trusted + patient built a giant. 🏆"),
 ]),
 ("c9","CHAPTER 9","The Castle of Trust","pages 71-80",[
   P("ti_c9_castle","Two kind old men appeared with a glow. Warren pointed at a castle. \"What keeps rivals out, Charlotte?\"","Walls! But made of what?"),
   MOAT([("🤝","Wall One: Trust","People buy precious things from a name they trust. A promise kept for decades is extremely hard to copy.",False),
         ("✨","Wall Two: Design & Craft","Beautiful, exact designs people love and rivals can't easily match — earned by years of skill.",False),
         ("🏬","Wall Three: Everywhere Shops","Welcoming shops in city after city where families feel safe. Building that web takes years.",False),
         ("⚠️","The Crack in the Wall","What could hurt it? Breaking the purity promise even once, or getting careless with quality. Trust is slow to build and fast to lose.",True)]),
   P("ti_c9_munger","Charlie tapped his head. \"Don't just ask how to WIN. Ask how you'd LOSE — then don't. Invert!\"","Think backwards?"),
   WOW("<b>Charlie's Inversion:</b> to keep a trusted maker great, imagine how it could be RUINED — a broken purity promise, sloppy quality — and carefully avoid every one. When you sell trust, being careful <i>is</i> the moat."),
   P("ti_c9_verdict","Warren nodded. \"Trusted, beautiful, everywhere — a fine castle, if it keeps its promise every single day.\"","I SEE the whole picture!"),
   NOTE("Charlotte's Secret Notebook · The Big Secret","Titan's WALLS: people TRUST it, its DESIGNS are loved, its SHOPS are everywhere. But Charlie's trick — imagine how it could be ruined (break the promise, get sloppy), then never do that. Invert! 🏰"),
 ]),
 ("c10","CHAPTER 10","Time All Around","pages 81-88",[
   P("ti_c10_wake","Charlotte woke in her own bed. The workshop was gone… but her clock ticked softly.","Was it real? It FELT real…"),
   P("ti_c10_diary","On the diary's page, a new line glowed — as if Grandpa Ben wrote it just for her.",None,'"Now you hear the tiny heart inside the tick. Well done."'),
   P("ti_c10_look","She ran outside. Every wrist, every clock tower, every shining ring — a hidden heart of exactness now.","Every tick has a tiny buzzing crystal inside!"),
   WOW("Next time you hear a watch tick, you'll know its secret: a tiny crystal buzzing the exact same count every second, patiently counted into perfect time — and a company that sells that same exactness as <b>trust</b>. That's <b>time on your wrist.</b> ⌚"),
   NOTE("Charlotte's Secret Notebook · What I Learned","➊ A quartz CRYSTAL buzzes the exact same number of times each second.<br>➋ A chip COUNTS the buzzes and ticks the hands; gears do the rest.<br>➌ Being EXACT is why a watch is trustworthy.<br>➍ With gold you can't check purity — so the real product is a trusted PROMISE.<br>➎ Titan sells precision + trust; Charlie's trick — figure out how you'd lose, then don't. 💛"),
 ]),
]

HOOK=("ti_c1_swirl","EVERY ORDINARY THING HIDES A SECRET.",
 "Charlotte found the tiny heart of time. But the compass is twitching again — toward the enormous things people build: soaring bridges, metro tunnels, giant machines. How do you build something SO big it seems impossible?",
 "NEXT ADVENTURE · The Builders of Giants →")

DIAGRAM='''<div class="panel wide" style="background:#f3eefb;">
<svg viewBox="0 0 820 360"><rect width="820" height="360" fill="#f3eefb"/>
<text x="410" y="38" text-anchor="middle" font-family="Bangers" font-size="24" fill="#8a5ad6">HOW A WATCH KEEPS PERFECT TIME</text>
<g><circle cx="150" cy="180" r="55" fill="#fff" stroke="#171717" stroke-width="4"/><path d="M130 180 q20 -30 40 0 t40 0" fill="none" stroke="#8a5ad6" stroke-width="4"/><text x="150" y="270" text-anchor="middle" font-family="Baloo 2" font-size="15" fill="#8a5ad6">1. CRYSTAL buzzes</text><text x="150" y="290" text-anchor="middle" font-family="Nunito" font-size="13" fill="#555">same count / second</text></g>
<g stroke="#171717" stroke-width="4" fill="#171717"><line x1="215" y1="180" x2="315" y2="180"/><path d="M311 172 L327 180 L311 188Z"/></g>
<g><rect x="330" y="140" width="120" height="80" rx="10" fill="#fff" stroke="#171717" stroke-width="4"/><text x="390" y="188" text-anchor="middle" font-family="Bangers" font-size="20" fill="#2aa15a">COUNT</text><text x="390" y="270" text-anchor="middle" font-family="Baloo 2" font-size="15" fill="#2aa15a">2. CHIP counts</text><text x="390" y="290" text-anchor="middle" font-family="Nunito" font-size="13" fill="#555">full heap = 1 second</text></g>
<g stroke="#171717" stroke-width="4" fill="#171717"><line x1="455" y1="180" x2="555" y2="180"/><path d="M551 172 L567 180 L551 188Z"/></g>
<g><circle cx="640" cy="180" r="55" fill="#fff" stroke="#171717" stroke-width="4"/><line x1="640" y1="180" x2="640" y2="145" stroke="#e8425a" stroke-width="4"/><line x1="640" y1="180" x2="668" y2="180" stroke="#171717" stroke-width="4"/><text x="640" y="270" text-anchor="middle" font-family="Baloo 2" font-size="15" fill="#e8425a">3. HANDS tick</text><text x="640" y="290" text-anchor="middle" font-family="Nunito" font-size="13" fill="#555">gears move them</text></g>
</svg><div class="figcap">A steady buzz, counted exactly, becomes the perfect tick of the hands.</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_theo"); 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/titan/_head.html").read()
    tail=open("/root/omahaindia.com/comics/site/book/titan/_tail.html").read()
    open(OUT,"w").write(head+"".join(body)+hook+tail)
    print("built",OUT)

if __name__=="__main__":
    build()
