#!/usr/bin/env python3
"""把主題表展開成固定結構的短影音腳本卡。"""

from __future__ import annotations

import argparse
import csv
import json
import sys
from pathlib import Path


def split_seconds(total: int) -> tuple[int, int, int]:
    hook = max(3, min(5, total // 6))
    cta = max(3, min(5, total // 6))
    body = total - hook - cta
    if body < 6:
        body = total - 6
        hook, cta = 3, 3
    return hook, body, cta


def main() -> int:
    parser = argparse.ArgumentParser(description="批次產出腳本卡")
    parser.add_argument("input", type=Path)
    parser.add_argument("-o", "--output", type=Path, required=True)
    parser.add_argument("--count", type=int, default=0, help="若主題不足，循環補到這個數量")
    args = parser.parse_args()

    with args.input.open(encoding="utf-8-sig", newline="") as handle:
        themes = list(csv.DictReader(handle))
    if not themes:
        print("沒有主題。", file=sys.stderr)
        return 1

    target = args.count or len(themes)
    cards = []
    for i in range(target):
        src = themes[i % len(themes)]
        total = int(src.get("seconds") or 20)
        hook, body, cta = split_seconds(total)
        cards.append(
            {
                "index": i + 1,
                "theme": src["theme"],
                "format": src.get("format", ""),
                "total_seconds": total,
                "hook_seconds": hook,
                "body_seconds": body,
                "cta_seconds": cta,
                "hook": f"用一句話點出「{src['theme']}」為什麼值得看完。",
                "body": f"用 {body} 秒講完重點，只留一個例子。",
                "cta": "用一句話告訴觀眾下一步：留言、收藏，或看置頂說明。",
            }
        )
    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.output.write_text(json.dumps(cards, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    print(f"寫出 {len(cards)} 張腳本卡到 {args.output}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
