#!/usr/bin/env python3
"""
VectorPM Friday — Veo + Remotion pipeline (CORRECT path)

Flow:
  1. POST /api/video/narrate-and-generate  →  5 Veo clips + TTS narration per scene
  2. POST /api/video/remotion-render        →  Remotion composes final branded video

Concept: It's Friday. With VectorPM your board is CLEAR.
Post: POV: It's Friday and your board is CLEAR 🎯 / Ship your week. Enjoy your weekend. / vectorpm.io
"""

import requests
import json
import time

BASE = "http://localhost:3071"

print("=== VectorPM Friday — Veo + Remotion Pipeline ===\n")

# ─── Scene definitions ────────────────────────────────────────────────────────
# characterPrompt: Filipino male professional, late 20s, white Oxford shirt
# lightingPalette: warm golden hour 5PM amber, office interior
scenes = [
    {
        "sceneId": "scene-1-hook",
        "narrationText": "P-O-V: It's 5 P-M on a Friday. And your board? Completely clear.",
        "framePrompt": (
            "Extreme close-up of a man's wrist wearing a minimalist watch, "
            "dial showing 4:59 PM, golden amber afternoon light streaming through office blinds, "
            "white Oxford shirt cuff visible, shallow depth of field, warm 5PM color grade, "
            "cinematic 9:16 vertical"
        ),
        "videoPrompt": (
            "Watch hand ticks from 4:59 to 5:00 PM | "
            "Slow macro push-in on the dial face | "
            "Golden office light holds steady, blinds shadow patterns static"
        ),
        "aspectRatio": "9:16",
        "durationSeconds": 6,
        "product": "vector",
        "cameraMovement": "dolly-in",
        "mood": "golden-hour",
        "platform": "tiktok",
        "focusSubject": "the watch face ticking to 5:00",
    },
    {
        "sceneId": "scene-2-clear-board",
        "narrationText": "Every task done. Every ticket closed. Ship your week.",
        "framePrompt": (
            "Medium shot of Filipino male professional late 20s leaning back in ergonomic office chair, "
            "arms raised in satisfied fist pump, laptop screen behind him showing empty task board with green checkmarks, "
            "warm amber office light at 5PM, white Oxford shirt, confident triumphant expression, "
            "cinematic 9:16 vertical"
        ),
        "videoPrompt": (
            "Man leans back in chair and raises fists in celebration | "
            "Camera slowly pulls back to reveal laptop screen with green completed tasks | "
            "Laptop screen glows softly, office background holds still"
        ),
        "aspectRatio": "9:16",
        "durationSeconds": 6,
        "product": "vector",
        "cameraMovement": "pull-back",
        "mood": "triumphant",
        "platform": "tiktok",
        "focusSubject": "the celebratory fist pump",
    },
    {
        "sceneId": "scene-3-laptop-close",
        "narrationText": "Close it. You're done for the week.",
        "framePrompt": (
            "Close-up of hands gently closing a laptop lid, "
            "warm golden light reflecting off the aluminium surface, "
            "white Oxford shirt cuffs, "
            "dark office desk background, "
            "cinematic warm 9:16 vertical, shallow depth of field"
        ),
        "videoPrompt": (
            "Hands smoothly close laptop lid from half-open to shut | "
            "Slow dramatic push-in as lid closes | "
            "Office desk surface and background hold completely still"
        ),
        "aspectRatio": "9:16",
        "durationSeconds": 4,
        "product": "vector",
        "cameraMovement": "dolly-in",
        "mood": "decisive",
        "platform": "tiktok",
        "focusSubject": "the laptop lid closing",
    },
    {
        "sceneId": "scene-4-pack-up",
        "narrationText": "Grab your bag. The weekend is calling.",
        "framePrompt": (
            "Medium shot Filipino male professional late 20s standing at desk, "
            "slinging leather bag over shoulder confidently, "
            "white Oxford shirt, "
            "warm golden hour light through window behind him, "
            "office in background soft bokeh, "
            "cinematic 9:16 vertical"
        ),
        "videoPrompt": (
            "Man lifts bag and slings it confidently over his shoulder | "
            "Camera holds steady with slight handheld drift as he pivots toward exit | "
            "Office bokeh background stays soft"
        ),
        "aspectRatio": "9:16",
        "durationSeconds": 4,
        "product": "vector",
        "cameraMovement": "handheld",
        "mood": "confident",
        "platform": "tiktok",
        "focusSubject": "the confident bag sling",
    },
    {
        "sceneId": "scene-5-exit",
        "narrationText": "VectorPM. Ship your week. Enjoy your weekend.",
        "framePrompt": (
            "Wide shot silhouette of Filipino male professional late 20s walking through glass office doors, "
            "warm golden hour light flooding in from outside, "
            "dramatic backlit silhouette, "
            "city skyline softly visible through glass, "
            "cinematic 9:16 vertical"
        ),
        "videoPrompt": (
            "Man strides confidently through glass doors into the golden light outside | "
            "Camera holds static as figure walks toward and through the doors | "
            "Bright golden exterior light floods in as doors open"
        ),
        "aspectRatio": "9:16",
        "durationSeconds": 6,
        "product": "vector",
        "cameraMovement": "static",
        "mood": "golden-hour",
        "platform": "tiktok",
        "focusSubject": "the silhouette walking into golden light",
    },
]

# ─── Step 1: narrate-and-generate ────────────────────────────────────────────
print("STEP 1: Generating Veo clips + TTS narration via narrate-and-generate...\n")

resp = requests.post(
    f"{BASE}/api/video/narrate-and-generate",
    json={"scenes": scenes},
    timeout=900,  # 15 min max
)

if not resp.ok:
    print(f"ERROR: narrate-and-generate failed: {resp.status_code}")
    print(resp.text)
    exit(1)

result = resp.json()
print(f"narrate-and-generate response:\n{json.dumps(result, indent=2)}\n")

generated_scenes = result.get("scenes", [])
if not generated_scenes:
    print("ERROR: No scenes returned from narrate-and-generate")
    exit(1)

print(f"✓ Got {len(generated_scenes)} scene(s) from orchestrator\n")

# ─── Step 2: Build Remotion scene configs ─────────────────────────────────────
print("STEP 2: Building Remotion scene configs...\n")

scene_labels = {
    "scene-1-hook":      ("POV: It's Friday 5PM", True,  ""),
    "scene-2-clear-board": ("Board clear. Every task done.", False, ""),
    "scene-3-laptop-close": ("Close it. You're done.", False, ""),
    "scene-4-pack-up":   ("The weekend is calling.", False, ""),
    "scene-5-exit":      ("Ship your week.", False, "vectorpm.io"),
}

# Duration map from scenes list
dur_map = {s["sceneId"]: s["durationSeconds"] for s in scenes}

remotion_scenes = []
for gs in generated_scenes:
    sid = gs["sceneId"]
    label, is_hook, cta = scene_labels.get(sid, ("", False, ""))
    video_filename = gs.get("videoFilename", "")
    audio_filename = gs.get("audioFilename")

    scene_cfg = {
        "videoPath": f"/home/aria/.openclaw/media/brandcast/videos/{video_filename}",
        "aspectRatio": "9:16",
        "durationSeconds": dur_map.get(sid, 6),
        "headline": label,
        "isHookScene": is_hook,
    }

    if is_hook:
        scene_cfg["hookText"] = "POV: It's Friday 5PM →"

    if cta:
        scene_cfg["ctaText"] = cta

    if audio_filename:
        scene_cfg["audioPath"] = f"/home/aria/.openclaw/media/brandcast/audio/{audio_filename}"

    remotion_scenes.append(scene_cfg)

    status = gs.get("status", "ok")
    print(f"  [{sid}] video={video_filename} audio={audio_filename or 'none'} status={status}")

print(f"\n✓ Built {len(remotion_scenes)} Remotion scene config(s)\n")

# ─── Step 3: Remotion render ──────────────────────────────────────────────────
print("STEP 3: Rendering via Remotion (BrandReel)...\n")

render_payload = {
    "scenes": remotion_scenes,
    "brand": {
        "primaryColor": "#ea580c",  # VectorPM orange
    },
    "compositionId": "BrandReel",
    "product": "VectorPM",
    "outputFilename": f"vectorpm-friday-remotion-{int(time.time())}.mp4",
}

render_resp = requests.post(
    f"{BASE}/api/video/remotion-render",
    json=render_payload,
    timeout=900,
)

if not render_resp.ok:
    print(f"ERROR: remotion-render failed: {render_resp.status_code}")
    print(render_resp.text)
    exit(1)

render_result = render_resp.json()
print(f"remotion-render response:\n{json.dumps(render_result, indent=2)}\n")

video_url = render_result.get("videoUrl", "")
filename = render_result.get("filename", "")
qa = render_result.get("qa")

print("=" * 60)
print(f"FINAL_VIDEO: /home/aria/.openclaw/media/brandcast/videos/{filename}")
if qa:
    print(f"QA: {qa.get('status')} ({qa.get('score', 0):.0f}/100)")
print("=" * 60)
