#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
批量生成封面模板预览图（CLI，对齐 Electron 资源目录生成）
"""

import os
import sys
import json
import argparse
import subprocess

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
COVER_GENERATOR = os.path.join(SCRIPT_DIR, "cover_generator.py")

COVER_STYLES = ["default", "blur-bg", "outline", "gradient", "split"]

STYLE_CONFIGS = {
    "default": {"titlePosition": "top", "titleColor": "#FFFFFF", "titleFontSize": 72},
    "blur-bg": {"titlePosition": "top", "titleColor": "#FFFFFF", "backgroundBlurEnabled": True},
    "outline": {
        "titlePosition": "top",
        "titleColor": "#FFFFFF",
        "titleStrokeWidth": 4,
        "titleStrokeColor": "#000000",
    },
    "gradient": {"titlePosition": "top", "titleColor": "#FFFFFF"},
    "split": {"titlePosition": "center", "titleColor": "#FFFFFF"},
}


def generate_all_cover_previews(video_path: str, preview_dir: str, demo_title: str) -> bool:
    os.makedirs(preview_dir, exist_ok=True)
    python_exe = os.environ.get("AICLIENT_PYTHON_PATH") or sys.executable
    ok_count = 0

    for style in COVER_STYLES:
        out_path = os.path.join(preview_dir, f"cover-preview-{style}.jpg")
        config = dict(STYLE_CONFIGS.get(style, STYLE_CONFIGS["default"]))
        cmd = [
            python_exe,
            COVER_GENERATOR,
            "--video",
            video_path,
            "--title",
            demo_title,
            "--output",
            out_path,
            "--config",
            json.dumps(config, ensure_ascii=False),
            "--timestamp",
            "1",
        ]
        try:
            r = subprocess.run(cmd, cwd=SCRIPT_DIR, capture_output=True, text=True, timeout=120)
            if r.returncode == 0 and os.path.isfile(out_path):
                print(f"✓ {out_path}", file=sys.stderr)
                ok_count += 1
            else:
                print(f"✗ {style}: {r.stderr or r.stdout}", file=sys.stderr)
        except Exception as e:
            print(f"✗ {style}: {e}", file=sys.stderr)

    return ok_count > 0


def main():
    parser = argparse.ArgumentParser(description="Generate cover template preview images")
    parser.add_argument("--video", required=True, help="Source video path")
    parser.add_argument("--output-dir", required=True, help="Output directory")
    parser.add_argument("--title", default="封面预览标题示例", help="Demo title text")
    args = parser.parse_args()

    if not os.path.isfile(args.video):
        print(f"Error: video not found: {args.video}", file=sys.stderr)
        sys.exit(1)

    success = generate_all_cover_previews(args.video, args.output_dir, args.title)
    sys.exit(0 if success else 1)


if __name__ == "__main__":
    main()
