#!/usr/bin/env python3
"""
Generate videos from extracted frames using Veo3.

Uses frame images as first frame for image-to-video generation.
"""

import os
import sys
import json
from pathlib import Path
from datetime import datetime

sys.path.insert(0, str(Path(__file__).parent.parent.parent / "scripts"))

from dotenv import load_dotenv
from laozhang_proxy import call_veo3_laozhang, download_video_laozhang

load_dotenv(Path(__file__).parent.parent.parent / ".env")


# Scene definitions for airport-reaper (9 frames, new order)
SCENES = [
    {
        "frame": 1,
        "caption": "Обычный дождливый день в аэропорту",
        "duration": 5,
        "motion": "Slow push-in on worker mowing grass with scythe. Rhythmic side-to-side sweeping motion. Rain drizzling, grass swaying. Peaceful mundane atmosphere.",
        "camera": "slow dolly in",
    },
    {
        "frame": 2,
        "caption": "Косарь делает свою работу",
        "duration": 4,
        "motion": "Medium shot, worker continues mowing methodically. Scythe sweeps through wet grass. Rain drips from hood. Calm routine work.",
        "camera": "static with subtle breathing",
    },
    {
        "frame": 3,
        "caption": "Як-42 выруливает на взлёт",
        "duration": 5,
        "motion": "Aircraft taxiing toward camera on wet runway. Engines whining louder. Rain on fuselage reflecting runway lights. Building anticipation.",
        "camera": "low angle, aircraft approaching",
    },
    {
        "frame": 4,
        "caption": "Работник отошёл в сторону",
        "duration": 4,
        "motion": "Worker stands still, waiting. Aircraft passes behind him. Wind from aircraft ruffles his poncho. Patient waiting pose.",
        "camera": "static wide shot",
    },
    {
        "frame": 5,
        "caption": "Он приветливо машет самолёту",
        "duration": 4,
        "motion": "Worker raises hand and waves friendly goodbye. Innocent cheerful gesture. Scythe held loosely in other hand.",
        "camera": "medium shot, static",
    },
    {
        "frame": 6,
        "caption": "Пассажиры в ужасе!",
        "duration": 4,
        "motion": "Passengers react in horror. Mouths open in screams. Some point at window, some cover faces. Pure panic spreading through cabin.",
        "camera": "handheld, chaotic",
    },
    {
        "frame": 7,
        "caption": "«Опять Семёныч вышел траву покосить...»",
        "duration": 5,
        "motion": "Pilot hears screaming, rolls eyes, sighs heavily with exasperated expression. He's seen this before. Tired resignation.",
        "camera": "medium close-up, static",
    },
    {
        "frame": 8,
        "caption": "Вид из иллюминатора...",
        "duration": 5,
        "motion": "POV through rain-streaked window. Dark hooded figure with scythe, arm raised. Fog swirls. Absolutely terrifying Grim Reaper apparition.",
        "camera": "static POV through window",
    },
    {
        "frame": 9,
        "caption": "— Ты бы хотя бы косу положил!",
        "duration": 5,
        "motion": "Worker holds radio to ear, puzzled expression. Lowers scythe slightly. Completely confused why they're upset. Innocent and oblivious.",
        "camera": "medium shot, slight push-in",
    },
]


def build_video_prompt(scene: dict) -> str:
    """Build Veo3 prompt from scene definition."""
    return f"""{scene['motion']}

Camera: {scene['camera']}
Style: dark comedy, cinematic, muted rainy color palette, ultra-realistic, shallow depth of field.
Duration: {scene['duration']} seconds.
NO text, NO speech, NO subtitles in the video."""


def generate_scene_video(
    frame_path: Path,
    scene: dict,
    api_key: str,
    output_dir: Path,
) -> Path:
    """Generate video for a single scene."""

    prompt = build_video_prompt(scene)

    print(f"\n=== Scene {scene['frame']}: {scene['caption']} ===")
    print(f"Frame: {frame_path}")
    print(f"Prompt: {prompt[:100]}...")

    # Create output directory
    scene_dir = output_dir / f"scene_{scene['frame']:02d}"
    scene_dir.mkdir(parents=True, exist_ok=True)

    # Save prompt
    prompt_path = scene_dir / "prompt.txt"
    with open(prompt_path, 'w') as f:
        f.write(f"Caption: {scene['caption']}\n\n")
        f.write(f"Motion: {scene['motion']}\n\n")
        f.write(f"Camera: {scene['camera']}\n\n")
        f.write(f"Full prompt:\n{prompt}\n")

    # Call Veo3
    try:
        result = call_veo3_laozhang(
            prompt=prompt,
            api_key=api_key,
            first_frame_path=str(frame_path),
            model="veo-3.1-fast-fl",  # Fast model with image input
            duration=scene['duration'],
        )

        # Download video
        video_url = result.get("uri")
        if video_url:
            video_path = scene_dir / "video.mp4"
            download_video_laozhang(video_url, str(video_path))
            print(f"  Video saved: {video_path}")

            # Save metadata
            meta_path = scene_dir / "metadata.json"
            with open(meta_path, 'w') as f:
                json.dump({
                    "scene": scene,
                    "video_url": video_url,
                    "frame_path": str(frame_path),
                    "timestamp": datetime.now().isoformat(),
                }, f, indent=2, ensure_ascii=False)

            return video_path
        else:
            print(f"  Error: No video URL in response")
            return None

    except Exception as e:
        print(f"  Error generating video: {e}")
        return None


def main():
    import argparse
    parser = argparse.ArgumentParser(description="Generate videos from frames")
    parser.add_argument("frames_dir", help="Directory with frame images")
    parser.add_argument("--output", "-o", help="Output directory", default=None)
    parser.add_argument("--scene", "-s", type=int, help="Generate only this scene (1-9)")
    args = parser.parse_args()

    api_key = os.environ.get("LAOZHANG_KEY")
    if not api_key:
        print("Error: LAOZHANG_KEY not set")
        sys.exit(1)

    frames_dir = Path(args.frames_dir)
    if not frames_dir.exists():
        print(f"Error: Frames directory not found: {frames_dir}")
        sys.exit(1)

    # Output directory
    if args.output:
        output_dir = Path(args.output)
    else:
        output_dir = frames_dir.parent / "videos" / "001"

    output_dir.mkdir(parents=True, exist_ok=True)
    print(f"Output: {output_dir}")

    # Generate videos
    scenes_to_process = SCENES
    if args.scene:
        scenes_to_process = [s for s in SCENES if s['frame'] == args.scene]
        if not scenes_to_process:
            print(f"Error: Scene {args.scene} not found")
            sys.exit(1)

    results = []
    for scene in scenes_to_process:
        frame_path = frames_dir / f"frame_{scene['frame']:02d}.jpg"
        if not frame_path.exists():
            print(f"Warning: Frame not found: {frame_path}")
            continue

        video_path = generate_scene_video(frame_path, scene, api_key, output_dir)
        results.append({
            "scene": scene['frame'],
            "caption": scene['caption'],
            "video": str(video_path) if video_path else None,
            "success": video_path is not None,
        })

    # Summary
    print("\n=== Summary ===")
    success = sum(1 for r in results if r['success'])
    print(f"Generated {success}/{len(results)} videos")

    for r in results:
        status = "✓" if r['success'] else "✗"
        print(f"  {status} Scene {r['scene']}: {r['caption']}")


if __name__ == "__main__":
    main()
