#!/usr/bin/env python3
"""Quick video producer for Austria vs Jordan match"""
import subprocess, os, json

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

# Match data
match = {
    "teams": "奥地利 vs 约旦",
    "score": "3-1",
    "winner": "奥地利",
    "goals": [
        {"min": "21'", "scorer": "约旦队", "detail": "约旦 1-0 领先", "score": "0-1"},
        {"min": "50'", "scorer": "奥地利", "detail": "奥地利扳平比分 1-1", "score": "1-1"},
        {"min": "76'", "scorer": "约旦队(乌龙)", "detail": "约旦后卫乌龙 奥地利 2-1", "score": "2-1"},
        {"min": "90+13'", "scorer": "奥地利", "detail": "奥地利锁定胜局 3-1", "score": "3-1"}
    ]
}

commentary = (
    "各位观众大家好，欢迎收看世界杯新闻。"
    f"在刚刚结束的世界杯小组赛中，奥地利队以3比1战胜了约旦队。"
    f"比赛第21分钟，约旦队率先破门，1比0领先。"
    f"第50分钟，奥地利队扳平比分。"
    f"第76分钟，约旦队后卫亚赞·阿拉布不慎打入乌龙球，奥地利队2比1反超。"
    f"比赛最后时刻，第90加13分钟，奥地利队再进一球，锁定胜局。"
    f"最终比分，奥地利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)

# Step 2: Get audio 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)
dur = float(r.stdout.strip())
print(f"Audio duration: {dur:.1f}s")

# Step 3: Create match video with ffmpeg - colored background + text + scoreboard
# First segment: Opening (0-dur/5)
# Use color source + drawtext for each segment
# We'll create 5 segments: opening, 3 goals, closing

seg_dur = dur / 5

# Create segments
segments = []
colors = ["#1a1a2e", "#16213e", "#0f3460", "#1a1a2e", "#16213e"]
texts = [
    f"2026世界杯\n{match['teams']}\n{match['score']}",
    f"⚽ 第{match['goals'][0]['min']}\n{match['goals'][0]['detail']}",
    f"⚽ 第{match['goals'][1]['min']}\n{match['goals'][1]['detail']}",
    f"⚽ 第{match['goals'][2]['min']}\n{match['goals'][2]['detail']}\n⚽ 第{match['goals'][3]['min']}\n{match['goals'][3]['detail']}",
    f"🏆 全场比分\n{match['teams']}\n{match['score']}\n{match['winner']}队获胜"
]

for i in range(5):
    out_file = f"{OUT}/seg_{i}.mp4"
    t = seg_dur if i < 4 else dur - seg_dur * 4
    
    # Escape text for ffmpeg
    txt = texts[i].replace("'", "'\\''").replace(":", "\\:").replace("%", "\\%")
    
    # Simple approach: use color + drawtext with multiple lines
    # First, replace newlines with actual drawtext calls
    lines = texts[i].split('\n')
    drawtext_filters = []
    y_pos = 200
    for line in lines:
        safe_line = line.replace("'", "'\\''").replace(":", "\\:").replace("%", "\\%").replace("{", "\\{").replace("}", "\\}")
        drawtext_filters.append(
            f"drawtext=text='{safe_line}':fontcolor=white:fontsize=48:"
            f"box=1:boxcolor=black@0.5:boxborderw=20:"
            f"x=(w-text_w)/2:y={y_pos}:"
            f"fontfile=/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc"
        )
        y_pos += 80
    
    filter_str = f"color=c={colors[i]}:s=1280x720:d={t:.1f}[bg];" + "[bg]" + ",".join(drawtext_filters) + "[v]"
    
    subprocess.run([
        "ffmpeg", "-y",
        "-f", "lavfi", "-i", f"color=c={colors[i]}:s=1280x720:d={t:.1f}",
        "-vf", ",".join(drawtext_filters),
        "-c:v", "libx264", "-preset", "ultrafast", "-crf", "28",
        "-pix_fmt", "yuv420p",
        "-t", f"{t:.1f}",
        out_file
    ], check=True, timeout=60, capture_output=True)
    segments.append(out_file)
    print(f"  seg_{i}: {t:.1f}s")

# Step 4: Concat segments
with open(f"{OUT}/concat.txt", "w") as f:
    for s in segments:
        f.write(f"file '{s}'\n")

print("Concat segments...")
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)

# Step 5: Mix video + TTS
print("Mix video + 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.mp4"
], check=True, timeout=60, capture_output=True)

# Step 6: Copy to web root
subprocess.run(["cp", f"{OUT}/final_news.mp4", "/root/austria_jordan_news.mp4"], timeout=10)

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