#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""make_subs.py — 生成横排简体、逐句浮现的歌词字幕（ASS）。

- 时间码取自 05-分镜脚本/shots.json（whisper 对齐后的逐句时间轴）
- 无歌词的镜头（前奏/间奏/尾奏）不显示歌词
- 样式：思源黑体、白字深描边、底部居中、淡入淡出，适合小朋友阅读

用法: python3 make_subs.py [--font "Noto Sans CJK SC"] [--size 62] [--out 05-分镜脚本/九九八十一-可爱版.ass]
"""
import argparse, json
from pathlib import Path

ROOT = Path(__file__).resolve().parent
FONT_DEFAULT = "Noto Sans CJK SC"


def ts(t):
    h = int(t // 3600); m = int(t % 3600 // 60); s = t % 60
    return f"{h:d}:{m:02d}:{s:05.2f}"


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--font", default=FONT_DEFAULT)
    ap.add_argument("--size", type=int, default=62)
    ap.add_argument("--out", default="05-分镜脚本/九九八十一-可爱版.ass")
    a = ap.parse_args()

    shots = json.load(open(ROOT / "05-分镜脚本/shots.json", encoding="utf-8"))["shots"]
    W, H = 1920, 1080
    head = f"""[Script Info]
ScriptType: v4.00+
PlayResX: {W}
PlayResY: {H}
WrapStyle: 2
ScaledBorderAndShadow: yes

[V4+ Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
Style: Lyric,{a.font},{a.size},&H00FFFFFF,&H00FFFFFF,&H003C3C3C,&H64000000,-1,0,0,0,100,100,1,0,1,3,1,2,120,120,84,1

[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
"""
    lines = []
    for s in shots:
        ly = (s.get("lyric") or "").strip()
        # 无歌词的镜头（前奏/间奏/尾奏）以及占位标记一律不出字幕
        if not ly or "间奏" in ly or ly.startswith("（") or ly.startswith("("):
            continue
        start, end = s["start"], s["end"]
        # 句首淡入 0.25s、句尾淡出 0.25s
        eff = "{\\fad(250,250)}"
        lines.append(f"Dialogue: 0,{ts(start)},{ts(end)},Lyric,,0,0,0,,{eff}{ly}")
    out = ROOT / a.out
    out.write_text(head + "\n".join(lines) + "\n", encoding="utf-8")
    print(f"已写 {out}（{len(lines)} 句歌词字幕）")


if __name__ == "__main__":
    main()
