#!/usr/bin/env python3
"""Produce France vs Senegal news video after match ends"""
import json, subprocess, os, sys, time

RESULT_FILE = "/root/match_result.json"
EVENT_FILE = "/root/match_events.json"
OUTPUT_DIR = "/root/news_clips"
os.makedirs(OUTPUT_DIR, exist_ok=True)

def log(msg):
    print(f"[PRODUCER] {msg}", flush=True)

def run_cmd(cmd, timeout=120):
    log(f"Running: {cmd[:80]}...")
    r = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
    if r.returncode != 0:
        log(f"WARN: exit {r.returncode}: {r.stderr[-200:]}")
    return r.stdout, r.stderr, r.returncode

def main():
    # Wait for result
    log("Waiting for match result...")
    for i in range(30):
        if os.path.exists(RESULT_FILE):
            with open(RESULT_FILE) as f:
                result = json.load(f)
            if result.get("state") == "post" or "Final" in result.get("detail", ""):
                log(f"Match done! {result['score']}")
                break
        time.sleep(60)
    else:
        log("Match not done yet, using last known result")
    
    with open(RESULT_FILE) as f:
        result = json.load(f)
    
    score = result["score"]
    sen = result["senegal"]
    fra = result["france"]
    events = result.get("events", [])
    
    # Build match recap
    teams = "塞内加尔 vs 法国"
    winner = "塞内加尔" if int(sen) > int(fra) else "法国" if int(fra) > int(sen) else "平局"
    
    commentary = f"各位观众大家好，欢迎收看世界杯新闻。"
    commentary += f"在刚刚结束的比赛中，{'法国队' if int(fra) >= int(sen) else '塞内加尔队'}以{score}战胜了对手。"
    
    if events:
        for ev in events:
            commentary += f"比赛进行到{ev['time']}，比分变为{ev['score']}。"
    
    commentary += f"最终比分，{'塞内加尔'}{sen}比{'法国'}{fra}，{'塞内加尔队' if int(sen) > int(fra) else '法国队'}取得了胜利。感谢收看。"
    
    log(f"Commentary: {commentary}")
    
    # Search for match video
    log("Searching for match video...")
    search_url = f"https://search.yahoo.co.jp/search?p=法国VS塞内加尔+世界杯2026+集锦&ei=UTF-8"
    r = subprocess.run(["curl", "-sL", search_url], capture_output=True, text=True, timeout=15)
    
    # Look for v.qq.com links
    html = r.stdout
    import re
    vqq_links = re.findall(r'https?://v\.qq\.com/[^\"\'<>\\s]+', html)
    log(f"Found {len(vqq_links)} v.qq links")
    
    video_file = None
    if vqq_links:
        url = vqq_links[0]
        log(f"Downloading: {url}")
        r = subprocess.run([
            "yt-dlp", url, "-o", f"{OUTPUT_DIR}/match_raw.mp4"
        ], capture_output=True, text=True, timeout=300)
        if os.path.exists(f"{OUTPUT_DIR}/match_raw.mp4"):
            video_file = f"{OUTPUT_DIR}/match_raw.mp4"
            log(f"Downloaded: {video_file}")
    
    if not video_file:
        log("No video found, searching more...")
        # Try more searches
        for q in [
            "France vs Senegal 2026 World Cup highlights",
            "France Senegal match video",
        ]:
            r = subprocess.run([
                "curl", "-sL",
                f"https://search.yahoo.co.jp/search?p={q.replace(' ', '+')}&ei=UTF-8"
            ], capture_output=True, text=True, timeout=15)
            links = re.findall(r'https?://[^\"\'<>\\s]+\.(?:mp4|m3u8)[^\"\'<>\\s]*', r.stdout)
            if links:
                r2 = subprocess.run([
                    "ffmpeg", "-headers", "Referer: https://search.yahoo.co.jp",
                    "-i", links[0], "-c", "copy", "-t", "120",
                    f"{OUTPUT_DIR}/match_raw.mp4"
                ], capture_output=True, text=True, timeout=300)
                if os.path.exists(f"{OUTPUT_DIR}/match_raw.mp4"):
                    video_file = f"{OUTPUT_DIR}/match_raw.mp4"
                    break
    
    if not video_file:
        log("Using fallback - Getty images slideshow")
        # Get photos from Getty
        r = subprocess.run([
            "curl", "-sL",
            f"https://search.yahoo.co.jp/search?p=France+Senegal+World+Cup+2026+Getty+Images&ei=UTF-8"
        ], capture_output=True, text=True, timeout=15)
        getty_urls = re.findall(r'https?://media\.gettyimages\.com/id/\d+/[^\"\'<>\\s]+', r.stdout)
        
        if getty_urls:
            # Download photos
            for i, url in enumerate(getty_urls[:5]):
                ext = url.split(".")[-1] if "." in url else "jpg"
                subprocess.run(["curl", "-sL", "-o", f"{OUTPUT_DIR}/photo_{i}.{ext}", url],
                             timeout=30)
            
            # Create slideshow
            input_list = "\n".join([f"file '{OUTPUT_DIR}/photo_{i}.jpg'" for i in range(min(5, len(getty_urls)))])
            with open(f"{OUTPUT_DIR}/photos.txt", "w") as f:
                # ffmpeg concat demuxer format
                for i in range(min(5, len(getty_urls))):
                    for ext in ["jpg", "jpeg", "png"]:
                        p = f"{OUTPUT_DIR}/photo_{i}.{ext}"
                        if os.path.exists(p):
                            f.write(f"file '{p}'\nduration 4\n")
                            break
            
            # Generate TTS first
            subprocess.run([
                "edge-tts", "--voice", "zh-CN-YunxiNeural", "--rate=+5%",
                "--text", commentary,
                "--write-media", f"{OUTPUT_DIR}/commentary.mp3"
            ], timeout=60)
            
            # Slideshow with TTS
            subprocess.run([
                "ffmpeg", "-y", "-f", "concat", "-safe", "0",
                "-i", f"{OUTPUT_DIR}/photos.txt",
                "-i", f"{OUTPUT_DIR}/commentary.mp3",
                "-vf", "scale=1280:720,fps=25",
                "-c:v", "libx264", "-preset", "fast", "-crf", "23",
                "-c:a", "aac", "-b:a", "128k",
                "-shortest", f"{OUTPUT_DIR}/final_news.mp4"
            ], timeout=120)
        else:
            log("No images found either, generating placeholder")
            # Generate TTS only (audio news)
            subprocess.run([
                "edge-tts", "--voice", "zh-CN-YunxiNeural", "--rate=+5%",
                "--text", commentary,
                "--write-media", f"{OUTPUT_DIR}/final_news.mp3"
            ], timeout=60)
            with open(f"{OUTPUT_DIR}/final_news.txt", "w") as f:
                f.write(f"Match Result: {score}\n\n{commentary}")
    else:
        # We have video - do the full production
        log("Producing news video from match footage...")
        
        # Step 1: Scene detection
        r = subprocess.run([
            "ffmpeg", "-i", video_file,
            "-filter:v", "select='gt(scene,0.3)',metadata=print:file=-",
            "-f", "null", "-"
        ], capture_output=True, text=True, timeout=120)
        scene_times = re.findall(r'pts_time:([\d.]+)', r.stderr + r.stdout)
        log(f"Scene changes at: {scene_times[:10]}")
        
        # Step 2: Generate TTS
        subprocess.run([
            "edge-tts", "--voice", "zh-CN-YunxiNeural", "--rate=+5%",
            "--text", commentary,
            "--write-media", f"{OUTPUT_DIR}/commentary.mp3"
        ], timeout=60)
        
        # Step 3: Simple cut - first 90 seconds of video + TTS
        subprocess.run([
            "ffmpeg", "-y", "-i", video_file,
            "-i", f"{OUTPUT_DIR}/commentary.mp3",
            "-c:v", "libx264", "-preset", "fast", "-crf", "23",
            "-c:a", "aac", "-b:a", "128k",
            "-shortest", f"{OUTPUT_DIR}/final_news.mp4"
        ], timeout=180)
    
    log("Done! Checking output...")
    result_file = f"{OUTPUT_DIR}/final_news.mp4"
    if os.path.exists(result_file):
        size = os.path.getsize(result_file)
        log(f"Output: {result_file} ({size/1024/1024:.1f}MB)")
    elif os.path.exists(f"{OUTPUT_DIR}/final_news.mp3"):
        log("Output: audio only")
    else:
        log("No output file!")
        sys.exit(1)

if __name__ == "__main__":
    main()
