#!/usr/bin/env python3
"""Austria vs Jordan news video v4 - with actual match footage!"""
import subprocess, os, json

SRC = "/root/news_clips/austria_final"
OUT = "/root/news_clips/austria_v4"
os.makedirs(OUT, exist_ok=True)

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

# Commentary script
commentary = (
    "各位观众大家好，欢迎收看世界杯新闻。"
    "在刚刚结束的世界杯小组赛中，奥地利队以3比1战胜了约旦队。"
    "比赛第20分钟，奥地利队施密德率先破门，1比0领先。"
    "第50分钟，约旦队扳平比分，1比1。"
    "第76分钟，约旦队阿拉布不慎打入乌龙球，奥地利队2比1再次领先。"
    "比赛最后时刻，第90加12分钟，奥地利队获得点球并罚进，将比分锁定为3比1。"
    "最终，奥地利队3比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)

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)
tts_dur = float(r.stdout.strip())
print(f"TTS: {tts_dur:.1f}s")

# We have these clips:
# 1. aut_goal_20.mp4 (23.7s) - Austria 1-0
# 2. jor_goal.mp4 (95.8s) - Jordan 1-1
# 3. aut_own_goal.mp4 (38.6s) - Own goal 2-1
# 4. jordan_pen.mp4 (60.7s) - Penalty 3-1 (check if this is correct)
# 5. aut_jor_4min.mp4 (291s) - Full 4-min highlights (use for extra footage)

# Strategy: Use the 4-min highlights as base, extract segments with scene detection
# Then insert individual goal clips for the key moments

# Step 1: Create segments from the 4-min highlights
# Use scene detection to find goal moments
print("Scene detection on 4-min highlights...")
r = subprocess.run([
    "ffmpeg", "-i", f"{SRC}/aut_jor_4min.mp4",
    "-filter:v", "select='gt(scene,0.3)',showinfo",
    "-f", "null", "-"
], capture_output=True, text=True, timeout=120)

# Extract scene change times
import re
scene_times = [float(x) for x in re.findall(r'pts_time:([\d.]+)', r.stderr + r.stdout)]
print(f"Scene changes at: {scene_times[:20]}")

# Step 2: Convert goal clips to 9:16 and add subtitles
goals = [
    {"file": f"{SRC}/aut_goal_20.mp4", "title": "⚽ 第20分钟", "subtitle": "奥地利 1-0 施密德进球", "bgm_keep": True},
    {"file": f"{SRC}/jor_goal.mp4", "title": "⚽ 第50分钟", "subtitle": "约旦 1-1 扳平比分", "bgm_keep": True},
    {"file": f"{SRC}/aut_own_goal.mp4", "title": "⚽ 第76分钟", "subtitle": "约旦 乌龙 2-1", "bgm_keep": True},
    {"file": f"{SRC}/jordan_pen.mp4", "title": "⚽ 90+12'", "subtitle": "奥地利 点球 3-1", "bgm_keep": True},
]

clip_files = []
total_clip_dur = 0

for i, g in enumerate(goals):
    out = f"{OUT}/clip_{i}.mp4"
    
    # Get original duration
    r = subprocess.run([
        "ffprobe", "-v", "error", "-show_entries", "format=duration",
        "-of", "csv=p=0", g["file"]
    ], capture_output=True, text=True, timeout=10)
    dur = float(r.stdout.strip())
    
    # Convert to 9:16 with subtitles
    # Scale to fill 1080x1920 (crop sides)
    title_esc = g["title"].replace(":", "\\:").replace("%", "\\%").replace("'", "'\\\\''")
    sub_esc = g["subtitle"].replace(":", "\\:").replace("%", "\\%").replace("'", "'\\\\''")
    
    # Top title bar
    filter_chain = (
        f"[0:v]scale=1920:1920:force_original_aspect_ratio=increase,"
        f"crop=1080:1920,"
        f"drawtext=text='{title_esc}':fontcolor=#FFD700:fontsize=48:"
        f"box=1:boxcolor=black@0.5:boxborderw=16:"
        f"x=(w-text_w)/2:y=80:fontfile={FONT},"
        f"drawtext=text='{sub_esc}':fontcolor=white:fontsize=40:"
        f"box=1:boxcolor=black@0.5:boxborderw=12:"
        f"x=(w-text_w)/2:y=h-120:fontfile={FONT}"
    )
    
    subprocess.run([
        "ffmpeg", "-y", "-i", g["file"],
        "-vf", filter_chain,
        "-c:v", "libx264", "-preset", "fast", "-crf", "23",
        "-c:a", "aac", "-b:a", "128k",
        "-pix_fmt", "yuv420p",
        out
    ], check=True, timeout=120, capture_output=True)
    
    clip_files.append(out)
    total_clip_dur += min(dur, 25)  # Cap each clip at 25s
    print(f"  Clip {i}: {g['subtitle']} ({min(dur,25):.0f}s)")

# Also get B-roll footage from the 4-min highlights for transitions
# Take opening kickoff (first 15s) and final score (last 15s)
print("\nExtracting opening and closing from highlights...")
subprocess.run([
    "ffmpeg", "-y", "-ss", "0", "-i", f"{SRC}/aut_jor_4min.mp4", "-t", "15",
    "-vf", f"scale=1920:1920:force_original_aspect_ratio=increase,crop=1080:1920",
    "-c:v", "libx264", "-preset", "fast", "-crf", "23",
    "-c:a", "aac", "-b:a", "128k",
    f"{OUT}/broll_open.mp4"
], timeout=60, capture_output=True)

subprocess.run([
    "ffmpeg", "-y", "-ss", "270", "-i", f"{SRC}/aut_jor_4min.mp4", "-t", "20",
    "-vf", f"scale=1920:1920:force_original_aspect_ratio=increase,crop=1080:1920",
    "-c:v", "libx264", "-preset", "fast", "-crf", "23",
    "-c:a", "aac", "-b:a", "128k",
    f"{OUT}/broll_close.mp4"
], timeout=60, capture_output=True)

# Step 3: Create intro and outro title cards
def make_title(text_lines, bg_color, duration, out_file):
    """Create a title card segment"""
    filters = []
    for i, line in enumerate(text_lines):
        safe = line.replace(":", "\\:").replace("%", "\\%").replace("'", "'\\\\''")
        y_pos = 400 + i * 120
        filters.append(
            f"drawtext=text='{safe}':fontcolor=white:fontsize=64:"
            f"box=1:boxcolor=black@0.5:boxborderw=20:"
            f"x=(w-text_w)/2:y={y_pos}:fontfile={FONT}"
        )
    
    filter_str = ",".join(filters)
    subprocess.run([
        "ffmpeg", "-y",
        "-f", "lavfi", "-i", f"color=c={bg_color}:s=1080x1920:d={duration}",
        "-vf", filter_str,
        "-c:v", "libx264", "-preset", "ultrafast", "-crf", "26",
        "-pix_fmt", "yuv420p", "-t", str(duration),
        out_file
    ], timeout=60, capture_output=True)

print("\nCreating title cards...")
make_title(["⚽ 2026世界杯", "奥地利  vs  约旦", "3  -  1"], "#1a1a2e", 8, f"{OUT}/title_open.mp4")
make_title(["🏆 全场结束", "奥地利 3 - 1 约旦", "奥地利队获胜"], "#0f3460", 8, f"{OUT}/title_close.mp4")

# Step 4: Concatenate everything
# Order: title → broll_open → clip_0 → clip_1 → clip_2 → clip_3 → broll_close → title_close
segments_order = [
    f"{OUT}/title_open.mp4",
    f"{OUT}/broll_open.mp4",
    *clip_files,
    f"{OUT}/broll_close.mp4",
    f"{OUT}/title_close.mp4"
]

with open(f"{OUT}/concat.txt", "w") as f:
    for seg in segments_order:
        f.write(f"file '{seg}'\n")

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

# Step 5: Mix with TTS audio + crowd background
# Keep original crowd audio at 30% volume, mix with TTS
print("Mixing audio...")
r = subprocess.run([
    "ffprobe", "-v", "error", "-show_entries", "format=duration",
    "-of", "csv=p=0", f"{OUT}/naked_video.mp4"
], capture_output=True, text=True, timeout=10)
video_dur = float(r.stdout.strip())

subprocess.run([
    "ffmpeg", "-y",
    "-i", f"{OUT}/naked_video.mp4",
    "-i", f"{OUT}/tts.mp3",
    "-filter_complex",
    "[0:a]volume=0.3[a0];[1:a]adelay=500|500[a1];[a0][a1]amix=inputs=2:duration=first:dropout_transition=2[a]",
    "-map", "0:v",
    "-map", "[a]",
    "-c:v", "copy",
    "-c:a", "aac", "-b:a", "128k",
    "-shortest",
    f"{OUT}/final_news_v4.mp4"
], timeout=120, capture_output=True)

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

size = os.path.getsize(f"{OUT}/final_news_v4.mp4")
print(f"\n🎉 DONE! {size/1024/1024:.1f}MB")
print("File: /root/austria_jordan_v4.mp4")
print(f"Duration: {video_dur:.0f}s")
