# -*- coding: utf-8 -*-
"""Dump the current LINES / POPS / LEADERBOARD straight out of make_movie.py
into a readable HTML review page, so edits to the script are the single
source of truth (this never hand-duplicates the content)."""
import importlib.util
import sys
from datetime import datetime, timedelta, timezone
from html import escape
from pathlib import Path

sys.stdout.reconfigure(encoding="utf-8")

spec = importlib.util.spec_from_file_location("make_movie", r"C:\ai\AUTOMOVIE\make_movie.py")
mm = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mm)  # safe: pipeline stages are gated by __main__ guard

TW = timezone(timedelta(hours=8))
VIDEO_T0 = datetime(2026, 8, 1, 8, 57, 1, tzinfo=TW)

# which lines changed text since the last TTS render (narration.json), so the
# reviewer knows which ones will need re-synthesis
old_by_i = {}
nf = Path(r"C:\ai\AUTOMOVIE\build\narration.json")
if nf.exists():
    import json
    for o in json.loads(nf.read_text(encoding="utf-8")):
        old_by_i[o["i"]] = o["text"]


def clock(vt):
    return (VIDEO_T0 + timedelta(seconds=vt)).strftime("%H:%M:%S")


def mmss(vt):
    return f"{int(vt)//60}:{vt%60:04.1f}"


rows = []
for i, (start, spoken, sub) in enumerate(mm.LINES):
    changed = old_by_i.get(i) != spoken
    tag = '<span class="chip changed">文字已改，待重錄</span>' if (i in old_by_i and changed) else \
          ('<span class="chip new">新增</span>' if i not in old_by_i else "")
    rows.append(f"""
    <tr>
      <td class="t"><div class="mmss">{mmss(start)}</div><div class="clock">{clock(start)}</div></td>
      <td class="spoken">{escape(spoken)}</td>
      <td class="sub">{escape(sub) if sub else '<span class="same">(同左)</span>'}</td>
      <td class="tag">{tag}</td>
    </tr>""")

def ass_colour_to_css(colour):
    # ASS is &HBBGGRR& -> CSS wants #RRGGBB
    hexpart = colour.strip("&H").strip("&")
    bb, gg, rr = hexpart[0:2], hexpart[2:4], hexpart[4:6]
    return f"#{rr}{gg}{bb}"


pop_rows = []
for start, dur, text, colour in mm.POPS:
    css = ass_colour_to_css(colour)
    pop_rows.append(f"""
    <tr>
      <td class="t"><div class="mmss">{mmss(start)}</div><div class="clock">{clock(start)}</div></td>
      <td><span class="swatch" style="display:inline-block;width:12px;height:12px;
          border-radius:3px;background:{css};margin-right:8px;vertical-align:middle;"></span>{escape(text)}</td>
      <td>{dur:.1f}s</td>
    </tr>""")

lb_rows = []
for pos, name, tm, kmh, pw, hr in mm.LEADERBOARD:
    me = name.startswith("TW 奈特")
    lb_rows.append(f"""
    <tr class="{'me' if me else ''}">
      <td>{escape(pos)}</td><td>{escape(name)}</td><td>{escape(tm)}</td>
      <td>{escape(kmh)}</td><td>{escape(pw)}</td><td>{escape(hr)}</td>
    </tr>""")

html = f"""<!doctype html>
<meta charset="utf-8">
<title>里嶺大橋 字幕腳本審閱</title>
<style>
  :root {{ color-scheme: light dark; }}
  body {{ font-family: -apple-system, "Microsoft JhengHei", sans-serif; max-width: 920px;
          margin: 40px auto; padding: 0 20px; line-height: 1.5; }}
  h1 {{ font-size: 1.5rem; }}
  h2 {{ font-size: 1.1rem; margin-top: 2.5rem; border-bottom: 2px solid #8883; padding-bottom: .3rem; }}
  table {{ width: 100%; border-collapse: collapse; margin-top: .8rem; font-size: .95rem; }}
  td, th {{ padding: 10px 8px; border-bottom: 1px solid #8883; vertical-align: top; text-align: left; }}
  .t {{ white-space: nowrap; width: 6.5em; }}
  .mmss {{ font-weight: 600; font-variant-numeric: tabular-nums; }}
  .clock {{ font-size: .78rem; opacity: .55; font-variant-numeric: tabular-nums; }}
  .spoken {{ }}
  .sub {{ opacity: .8; }}
  .same {{ opacity: .4; font-style: italic; }}
  .chip {{ font-size: .72rem; padding: 2px 8px; border-radius: 999px; white-space: nowrap; }}
  .chip.changed {{ background: #f5a62333; color: #b8860b; border: 1px solid #f5a62366; }}
  .chip.new {{ background: #4caf5033; color: #2e7d32; border: 1px solid #4caf5066; }}
  .note {{ background: #f5a62318; border-left: 3px solid #f5a623; padding: .8rem 1rem; margin: 1rem 0; font-size: .92rem; }}
  .note b {{ display: block; margin-bottom: .3rem; }}
  tr.me {{ background: #00c8ff14; font-weight: 600; }}
  .legend {{ font-size: .85rem; opacity: .7; margin-top: .5rem; }}
</style>

<h1>里嶺大橋 20260801 — 字幕 / 旁白腳本審閱</h1>
<p class="legend">直接對照 make_movie.py 現在的內容產生，不是另外手打的版本，改完程式重跑這頁就會跟著更新。</p>

<div class="note">
  <b>待你確認的兩個問題</b>
  1) 「片頭一開始就計時」跟實際 GPS 數據對不上：從影片開頭算 159 秒，均速只有 48.0 km/h；
     但 55→214 秒這個窗口均速 50.16 km/h，跟排行榜的 50.2 幾乎完全吻合。目前旁白已經拿掉「計時開始」這種宣告式分界，
     但時間標記仍以 55~214 秒為準——如果你認為真正的起點是別的時間點，請告訴我對應的真實時鐘時間。<br><br>
  2) 片頭字卡 ({mmss(0.9)}) 還留著「距離冠軍　只差 4 秒」，片尾排行榜表格也還列著冠軍等其他人的瓦數/心率。
     這兩處是畫面文字，不是旁白，我先保留沒動——要一併拿掉嗎？
</div>

<h2>旁白 / 字幕逐句（{len(mm.LINES)} 句）</h2>
<table>
  <tr><th>時間</th><th>口白（TTS 唸的）</th><th>畫面字幕（如果不同）</th><th></th></tr>
  {"".join(rows)}
</table>

<h2>畫面彈出文字（POPS，{len(mm.POPS)} 個）</h2>
<table>
  <tr><th>時間</th><th>內容</th><th>停留</th></tr>
  {"".join(pop_rows)}
</table>

<h2>片尾排行榜卡</h2>
<table>
  <tr><th>名次</th><th>選手</th><th>成績</th><th>均速</th><th>功率</th><th>心率</th></tr>
  {"".join(lb_rows)}
</table>
"""

out = Path(r"C:\ai\AUTOMOVIE\字幕審閱.html")
out.write_text(html, encoding="utf-8")
print(f"wrote {out}  ({len(mm.LINES)} lines, {len(mm.POPS)} pops)")
