#!/usr/bin/env python3
"""Austria vs Jordan news video v3 - with real match photos in 9:16"""
import subprocess, os

IMG_DIR = "/root/news_clips/austria_images"
OUT = "/root/news_clips/austria_v3"
os.makedirs(OUT, exist_ok=True)

FONT = "/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc"
W, H = 1080, 1920  # 9:16

# Match photos downloaded from Guardian
photos = sorted([f for f in os.listdir(IMG_DIR) if f.endswith('.jpg')])
print(f"Found {len(photos)} photos: {photos}")

# Commentary
commentary = (
    "各位观众大家好，欢迎收看世界杯新闻。"
    "在刚刚结束的世界杯小组赛中，奥地利队以3比1战胜了约旦队。"
    "比赛第21分钟，奥地利队率先破门，1比0领先。"
    "第50分钟，约旦队扳平比分，1比1。"
    "第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 real photos as backgrounds
# 6 segments with photos rotating as backgrounds
segments = [
    # (ratio, title, subtitle, overlay_text, photo)
    (0.15, "⚽ 2026世界杯", "奥地利 3 - 1 约旦", "开场", photos[0]),
    (0.17, "⚽ 第21分钟", "奥地利 进球", "1 - 0", photos[1]),
    (0.17, "⚽ 第50分钟", "约旦 进球", "1 - 1", photos[1]),
    (0.17, "⚽ 第76分钟", "约旦 乌龙球", "2 - 1", photos[2]),
    (0.17, "⚽ 90+12'", "奥地利 点球", "3 - 1", photos[0]),
    (0.17, "🏆 全场结束", "奥地利队获胜", "3 - 1", photos[2]),
]

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

for i, (ratio, title, subtitle, score_str, photo) in enumerate(segments):
    t = total_dur * ratio
    if i == len(segments) - 1:
        t = total_dur - sum(total_dur * s[0] for s in segments[:-1])
    
    photo_path = os.path.join(IMG_DIR, photo)
    out_file = f"{OUT}/seg_{i}.mp4"
    print(f"  seg_{i}: {t:.1f}s - {subtitle}")
    
    # Build overlay: photo scaled to fill 9:16 + dark overlay + text
    # First scale photo to fill width (1080), then crop to 1920 height
    # Then add dark overlay and text
    
    filters = []
    
    # Scale photo to 1080p wide, then crop to 9:16
    filters.append(
        f"[0:v]scale={W}:{H}:force_original_aspect_ratio=increase,crop={W}:{H}"
    )
    
    # Add semi-transparent dark overlay for readability
    filters.append(
        f"drawbox=x=0:y=0:w={W}:h={H}:color=black@0.45:t=fill"
    )
    
    # Score text - top
    title_esc = esc(title)
    filters.append(
        f"drawtext=text='{title_esc}':fontcolor=#FFD700:fontsize=56:"
        f"box=1:boxcolor=black@0.5:boxborderw=20:"
        f"x=(w-text_w)/2:y=250:"
        f"fontfile={FONT}"
    )
    
    # Big score in the middle
    if i == 0:
        # Opening - show team names and score
        main_text = esc("奥地利 vs 约旦")
        sub_esc = esc("3 - 1")
        filters.append(
            f"drawtext=text='{main_text}':fontcolor=white:fontsize=72:"
            f"box=1:boxcolor=black@0.5:boxborderw=28:"
            f"x=(w-text_w)/2:y=(h-text_h)/2-100:"
            f"fontfile={FONT}"
        )
        filters.append(
            f"drawtext=text='{sub_esc}':fontcolor=#00FF00:fontsize=96:"
            f"x=(w-text_w)/2:y=(h-text_h)/2+80:"
            f"fontfile={FONT}"
        )
    else:
        sub_esc = esc(subtitle)
        score_esc = esc(score_str)
        
        # Event name
        filters.append(
            f"drawtext=text='{sub_esc}':fontcolor=white:fontsize=64:"
            f"box=1:boxcolor=black@0.5:boxborderw=24:"
            f"x=(w-text_w)/2:y=(h-text_h)/2-80:"
            f"fontfile={FONT}"
        )
        
        # Score
        filters.append(
            f"drawtext=text='{score_esc}':fontcolor=#FFD700:fontsize=80:"
            f"x=(w-text_w)/2:y=(h-text_h)/2+60:"
            f"fontfile={FONT}"
        )
    
    # Bottom watermark
    watermark = esc("世界杯新闻 · 奥地利 vs 约旦")
    filters.append(
        f"drawtext=text='{watermark}':fontcolor=gray:fontsize=28:"
        f"x=(w-text_w)/2:y=h-150:"
        f"fontfile={FONT}"
    )
    
    filter_str = ",".join(filters)
    
    subprocess.run([
        "ffmpeg", "-y",
        "-loop", "1", "-i", photo_path,
        "-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
print("Concatenating...")
with open(f"{OUT}/concat.txt", "w") as f:
    for i in range(len(segments)):
        f.write(f"file '{OUT}/seg_{i}.mp4'\n")

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 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_v3.mp4"
], check=True, timeout=60, capture_output=True)

subprocess.run(["cp", f"{OUT}/final_news_v3.mp4", "/root/austria_jordan_v3.mp4"], timeout=10)

size = os.path.getsize(f"{OUT}/final_news_v3.mp4")
print(f"\nDONE! {size/1024/1024:.1f}MB - /root/austria_jordan_v3.mp4")
