#!/usr/bin/env python3
"""Austria vs Jordan news video v2 - 9:16 vertical, correct goal order"""
import subprocess, os, json

OUT = "/root/news_clips/austria_v2"
os.makedirs(OUT, exist_ok=True)

# CORRECT goal order:
# 21' - Austria scores (1-0)
# 50' - Jordan scores (1-1)
# 76' - Jordan own goal (2-1 Austria)
# 90+12' - Austria penalty (3-1 Austria)

commentary = (
    "各位观众大家好，欢迎收看世界杯新闻。"
    "在刚刚结束的世界杯小组赛中，奥地利队以3比1战胜了约旦队。"
    "比赛第21分钟，奥地利队率先破门，1比0领先。"
    "第50分钟，约旦队扳平比分。"
    "第76分钟，约旦队打入乌龙球，奥地利队2比1再次领先。"
    "比赛最后时刻，第90加12分钟，奥地利队获得点球并罚进，将比分锁定为3比1。"
    "最终，奥地利队3比1战胜约旦队，取得了一场关键胜利。感谢收看。"
)

# Step 1: Generate TTS
print("Generating TTS...")
subprocess.run([
    "edge-tts", "--voice", "zh-CN-YunxiNeural", "--rate=+5%",
    "--text", commentary,
    "--write-media", f"{OUT}/tts.mp3"
], check=True, timeout=60)

# Get duration
r = subprocess.run([
    "ffprobe", "-v", "error", "-show_entries", "format=duration",
    "-of", "default=noprint_wrappers=1:nokey=1", f"{OUT}/tts.mp3"
], capture_output=True, text=True, timeout=10)
total_dur = float(r.stdout.strip())
print(f"Duration: {total_dur:.1f}s")

# Step 2: Create segments with team logos, scoreboard and goal graphics
# 9:16 = 1080x1920 portrait

segments_info = [
    # (duration_ratio, title_text, subtitle, bg_color)
    (0.15, "⚽ 2026世界杯", "奥地利 vs 约旦\n3 - 1", "#1a1a2e"),      # Opening
    (0.17, "⚽ 第21分钟", "🇦🇹 奥地利 进球\n1 - 0", "#16213e"),       # Goal 1 - Austria
    (0.17, "⚽ 第50分钟", "🇯🇴 约旦 进球\n1 - 1", "#0f3460"),        # Goal 2 - Jordan
    (0.17, "⚽ 第76分钟", "🇯🇴 约旦 乌龙球\n2 - 1", "#1a1a2e"),      # Goal 3 - Own Goal
    (0.17, "⚽ 90+12'", "🇦🇹 奥地利 点球\n3 - 1", "#16213e"),        # Goal 4 - Austria Penalty
    (0.17, "🏆 全场结束", "奥地利 3 - 1 约旦\n奥地利队获胜", "#0f3460")  # Closing
]

colors = ["#1a1a2e", "#16213e", "#0f3460", "#533483", "#16213e", "#1a1a2e"]

# W = 1080, H = 1920 for 9:16
W, H = 1080, 1920

# Common font
FONT = "/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc"

def esc(text):
    """Escape for ffmpeg drawtext"""
    return text.replace(":", "\\:").replace("'", "'\\\\''").replace("%", "\\%").replace("{", "\\{").replace("}", "\\}")

# Create each segment
for i, (ratio, title, subtitle, color) in enumerate(segments_info):
    t = total_dur * ratio
    if i == len(segments_info) - 1:
        t = total_dur - sum(total_dur * s[0] for s in segments_info[:-1])
    
    out_file = f"{OUT}/seg_{i}.mp4"
    print(f"  seg_{i}: {t:.1f}s - {title}")
    
    # Build a nice scoreboard-like display
    lines = [title, "", subtitle, ""]
    
    # Draw main title (big, top area)
    title_text = esc(title)
    subtitle_text = esc(subtitle)
    
    filters = []
    
    # Top subtitle (ball + title)
    filters.append(
        f"drawtext=text='{title_text}':fontcolor=#FFD700:fontsize=64:"
        f"box=1:boxcolor=black@0.4:boxborderw=24:"
        f"x=(w-text_w)/2:y=300:"
        f"fontfile={FONT}"
    )
    
    # Main score text (center)
    filters.append(
        f"drawtext=text='{subtitle_text}':fontcolor=white:fontsize=72:"
        f"box=1:boxcolor=black@0.5:boxborderw=32:"
        f"x=(w-text_w)/2:y=(h-text_h)/2-50:"
        f"fontfile={FONT}"
    )
    
    # Bottom hint
    hint = "世界杯新闻" if i == 0 else "奥地利 vs 约旦 · 世界杯2026"
    hint_text = esc(hint)
    filters.append(
        f"drawtext=text='{hint_text}':fontcolor=gray:fontsize=36:"
        f"x=(w-text_w)/2:y=h-200:"
        f"fontfile={FONT}"
    )
    
    # Bottom dividing line effect
    filters.append(
        f"drawtext=text='───':fontcolor=#FFD700:fontsize=48:"
        f"x=(w-text_w)/2:y=h-300:"
        f"fontfile={FONT}"
    )
    
    filter_str = ",".join(filters)
    
    subprocess.run([
        "ffmpeg", "-y",
        "-f", "lavfi", "-i", f"color=c={color}:s={W}x{H}:d={t:.1f}",
        "-vf", filter_str,
        "-c:v", "libx264", "-preset", "ultrafast", "-crf", "26",
        "-pix_fmt", "yuv420p",
        "-t", f"{t:.1f}",
        out_file
    ], check=True, timeout=120, capture_output=True)

# Concat segments
with open(f"{OUT}/concat.txt", "w") as f:
    for i in range(len(segments_info)):
        f.write(f"file '{OUT}/seg_{i}.mp4'\n")

print("Concatenating...")
subprocess.run([
    "ffmpeg", "-y", "-f", "concat", "-safe", "0",
    "-i", f"{OUT}/concat.txt", "-c", "copy",
    f"{OUT}/naked_video.mp4"
], check=True, timeout=60, capture_output=True)

# Mix with audio
print("Mixing audio...")
subprocess.run([
    "ffmpeg", "-y",
    "-i", f"{OUT}/naked_video.mp4",
    "-i", f"{OUT}/tts.mp3",
    "-c:v", "copy",
    "-c:a", "aac", "-b:a", "128k",
    "-shortest",
    f"{OUT}/final_news_v2.mp4"
], check=True, timeout=60, capture_output=True)

# Copy to root
subprocess.run(["cp", f"{OUT}/final_news_v2.mp4", "/root/austria_jordan_v2.mp4"], timeout=10)

size = os.path.getsize(f"{OUT}/final_news_v2.mp4")
print(f"\nDONE! Output: {size/1024/1024:.1f}MB")
print("File: /root/austria_jordan_v2.mp4")
