#!/usr/bin/env python3
"""Stage the 4 demo scenes as self-contained HTML (states of the real player UI)."""
import os, json, pathlib

ROOT = pathlib.Path(__file__).resolve().parent.parent
OUT = pathlib.Path('/tmp/ttsdemo/scenes'); OUT.mkdir(parents=True, exist_ok=True)
player = (ROOT / 'src/player.html').read_text().replace('{{VERSION}}', '1.9.20')

CAPTION_CSS = """
<style>.demo-cap{position:fixed;top:52px;left:50%;transform:translateX(-50%);z-index:99;
background:rgba(13,17,23,.92);border:1px solid #2b3a52;border-radius:999px;padding:6px 18px;
font:600 13.5px 'Familjen Grotesk',system-ui,sans-serif;color:#7fe3dd;box-shadow:0 6px 24px rgba(0,0,0,.5)}</style>
"""

def cap(text):
    return CAPTION_CSS + f'<div class="demo-cap">{text}</div>'

WORDS1 = ("This is the flight-search thread. Round trip to Denver looks best on Tuesday: "
          "two forty five nonstop, four hundred twelve dollars on United. Want me to hold it?")

# ---- scene 1: player mid-karaoke ----
inj1 = cap("One shared player for all your AI threads") + """
<script>window.addEventListener('load',function(){
var words=%s.split(" ");
try{applyClip({id:1,title:'flight-answer.mp3',meta:'en-US-AndrewNeural',label:'flight-search',
  desc:'Denver flight options — best is Tue 2:45pm nonstop $412',words:words});}catch(e){}
var a=document.getElementById('a'); a.dispatchEvent(new Event('playing'));
var old=document.getElementById('live'); if(old){var neo=old.cloneNode(false);neo.className='led ok';neo.id='live2';old.parentNode.replaceChild(neo,old);}
var di=document.getElementById('diag'); if(di)di.remove();
var spans=document.querySelectorAll('.transcript w'); var i=0; var total=16.0; var t=0;
setInterval(function(){
  var s=document.getElementById('status'); if(s){s.textContent='playing';s.className='pill playing';}
  document.body.classList.add('is-playing');
  var pi=document.querySelector('#playicon path'); if(pi)pi.setAttribute('d','M6 5h4v14H6zM14 5h4v14h-4z');
},80);
setInterval(function(){
  if(i<spans.length){ spans.forEach(function(el,k){el.classList.toggle('active',k===i);el.classList.toggle('spoken',k<i);}); i++; }
  t=Math.min(total,t+0.42);
  var c=document.getElementById('cur'); if(c)c.textContent='0:'+String(Math.floor(t)).padStart(2,'0');
  var d=document.getElementById('dur'); if(d)d.textContent='0:16';
  var sk=document.getElementById('seek'); if(sk)sk.value=Math.round(t/total*1000);
},420);
});</script>""" % json.dumps(WORDS1)
(OUT / 'player.html').write_text(player.replace('</body>', inj1 + '</body>'))

# ---- scene 3: history + replay preempt ----
inj3 = cap("Missed a clip? It waits for you in History") + """
<script>window.addEventListener('load',function(){
var words="Missed clips wait for you right here in the history, one tap from playing again.".split(" ");
try{applyClip({id:1,title:'reply.mp3',meta:'en-US-AndrewNeural',label:'Adom-TTS',desc:'how the replayable history works',words:words});}catch(e){}
var now=Date.now();
renderHistory([
 {seq:1,ts_ms:now-35000,label:'Adom-TTS',desc:'how the replayable history works',verdict:'ok',dur_s:11.2},
 {seq:2,ts_ms:now-160000,label:'flight-search',desc:'Denver flight options — best is Tue 2:45pm nonstop $412',verdict:'ok',dur_s:16.4},
 {seq:3,ts_ms:now-380000,label:'deploy-watch',desc:'nightly deploy finished, zero errors',verdict:'no-playback',dur_s:24.0},
 {seq:4,ts_ms:now-1500000,label:'login-bug',desc:'login fix verified on prod',verdict:'ok',dur_s:19.8}
], now);
var a=document.getElementById('a'); a.dispatchEvent(new Event('playing'));
var old=document.getElementById('live'); if(old){var neo=old.cloneNode(false);neo.className='led ok';neo.id='live2';old.parentNode.replaceChild(neo,old);}
var di=document.getElementById('diag'); if(di)di.remove();
setInterval(function(){var s=document.getElementById('status'); if(s){s.textContent='playing';s.className='pill playing';} document.body.classList.add('is-playing');
  var pi=document.querySelector('#playicon path'); if(pi)pi.setAttribute('d','M6 5h4v14H6zM14 5h4v14h-4z');},80);
// beat: 3s in, pulse the missed row; 6s in, flash its replay button; 8s, swap to replay
setTimeout(function(){var rows=document.querySelectorAll('.hist-row'); if(rows[2]){rows[2].style.transition='background .4s';rows[2].style.background='rgba(212,160,23,.12)';}},3000);
setTimeout(function(){var b=document.querySelectorAll('.hist-replay')[2]; if(b){b.style.transition='transform .25s, background .25s';b.style.background='rgba(0,184,177,.35)';b.style.transform='scale(1.35)';setTimeout(function(){b.style.transform='scale(1)';b.textContent='✓';},450);}},6000);
setTimeout(function(){
  var w2="nightly deploy finished, zero errors, all services healthy after the rollout.".split(" ");
  try{applyClip({id:2,title:'deploy-note.mp3',meta:'en-US-AndrewNeural',label:'deploy-watch',desc:'(replay) nightly deploy finished, zero errors',words:w2});}catch(e){}
  var a2=document.getElementById('a'); a2.dispatchEvent(new Event('playing'));
  var spans=document.querySelectorAll('.transcript w'); var i=0;
  setInterval(function(){ if(i<spans.length){spans.forEach(function(el,k){el.classList.toggle('active',k===i);el.classList.toggle('spoken',k<i);}); i++;} },430);
},8200);
});</script>"""
(OUT / 'history.html').write_text(player.replace('</body>', inj3 + '</body>'))

# ---- scene 2: verified send (terminal typing) ----
term = """<!doctype html><html><head><style>
body{margin:0;background:#0d1117;display:flex;align-items:center;justify-content:center;min-height:100vh;font-family:ui-monospace,Menlo,monospace}
.term{width:820px;background:#0a0e14;border:1px solid #2b3a52;border-radius:12px;box-shadow:0 18px 50px rgba(0,0,0,.55);overflow:hidden}
.bar{height:34px;background:#161b22;border-bottom:1px solid #2b3a52;display:flex;align-items:center;padding:0 12px;color:#8b98a5;font-size:12px}
.bar .dot{width:10px;height:10px;border-radius:50%;background:#2b3a52;margin-right:6px}
pre{margin:0;padding:18px 20px;font-size:14px;line-height:1.7;color:#e6edf3;white-space:pre-wrap;min-height:330px}
.p{color:#7fe3dd}.c{color:#8b98a5}.g{color:#3fb950}
.cursor{display:inline-block;width:8px;height:16px;background:#7fe3dd;vertical-align:-2px;animation:bl 1s steps(1) infinite}
@keyframes bl{50%{opacity:0}}
CAPCSS</style></head><body>
CAPDIV
<div class="term"><div class="bar"><span class="dot"></span><span class="dot"></span><span class="dot"></span>claude — adom-tts</div><pre id="t"><span class="p">$</span> <span id="cmd"></span><span class="cursor" id="cur"></span><span id="out"></span></pre></div>
<script>
var CMD = 'adom-tts say "This is the flight-search thread — best Denver option is Tuesday 2:45pm nonstop." \\\\\\n    --thread "flight-search" --desc "Denver flight options" \\\\\\n    --out /tmp/answer.mp3 --play --confirm';
var i=0;
var typer=setInterval(function(){
  if(i<CMD.length){ document.getElementById('cmd').textContent=CMD.slice(0,++i); }
  else clearInterval(typer);
},34);
var OUT=[
 [5200,'\\n\\n→ /tmp/answer.mp3 (98304 bytes, cache=miss, hash=a1b2c3d4e5f6)'],
 [6100,'\\n<span class="c"># ACCEPTED "answer.mp3" — next up in the shared player.</span>'],
 [7000,'\\n<span class="c"># to KNOW it played: adom-tts check answer.mp3 — or --confirm blocks until heard.</span>'],
 [10300,'\\n\\n<span class="g">✓ CONFIRMED: "answer.mp3" played fully to the human (16/16s)</span>']
];
OUT.forEach(function(o){ setTimeout(function(){ document.getElementById('out').innerHTML+=o[1]; document.getElementById('cur').style.display='none'; }, o[0]); });
</script></body></html>"""
term = term.replace('CAPCSS', CAPTION_CSS.replace('<style>','').replace('</style>',''))
term = term.replace('CAPDIV', '<div class="demo-cap">Playback is verified, never assumed</div>')
(OUT / 'verify.html').write_text(term)

# ---- scene 4: outro (hero slow zoom + install typing) ----
hero_path = ROOT / 'screenshots/hero-v3.png'
outro = """<!doctype html><html><head><style>
body{margin:0;background:#0d1117;min-height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;overflow:hidden;font-family:ui-monospace,Menlo,monospace}
.wrap{width:860px;border-radius:14px;overflow:hidden;border:1px solid #2b3a52;box-shadow:0 18px 60px rgba(0,0,0,.6)}
img{width:100%%;display:block;animation:zoom 14s linear forwards}
@keyframes zoom{from{transform:scale(1)}to{transform:scale(1.07)}}
.inst{margin-top:26px;font-size:16px;color:#7fe3dd;background:#0a0e14;border:1px solid #2b3a52;border-radius:10px;padding:12px 22px}
.cursor{display:inline-block;width:8px;height:16px;background:#7fe3dd;vertical-align:-2px;animation:bl 1s steps(1) infinite}
@keyframes bl{50%%{opacity:0}}
</style></head><body>
<div class="wrap"><img src="file://%s"></div>
<div class="inst"><span id="cmd"></span><span class="cursor"></span></div>
<script>
var CMD='adom-wiki pkg install adom/adom-tts'; var i=0;
setTimeout(function(){ var t=setInterval(function(){ if(i<CMD.length){document.getElementById('cmd').textContent=CMD.slice(0,++i);} else clearInterval(t); },50); },1500);
</script></body></html>""" % str(hero_path)
(OUT / 'outro.html').write_text(outro)

print("scenes:", sorted(p.name for p in OUT.iterdir()))