#!/usr/bin/env python3
"""Render pilot reel 1080x1920 (9:16), 5 scene, ffmpeg per scene + concat."""
import subprocess, os, textwrap, sys

ROOT = "/home/mantapman/.hermes/profiles/atun/workspace/uky_video_pilot"
OUT = os.path.join(ROOT, "pilot_video_1.mp4")
FONT = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
FONT_REG = "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"
FPS = 30
W, H = 1080, 1920
TMP = os.path.join(ROOT, ".render_tmp")
os.makedirs(TMP, exist_ok=True)

def write_text(name, content):
    p = os.path.join(TMP, name)
    with open(p, "w") as f:
        f.write(content)
    return p

def drawtext_args(txtfile, y, size, color="white", box=True, font=FONT, alpha="0.42"):
    args = ["drawtext=textfile='%s':fontfile='%s':fontsize=%d:fontcolor=%s:x=(w-text_w)/2:y=%d"
            % (txtfile, font, size, color, y)]
    if box:
        args[0] += ":box=1:boxcolor=black@%s:boxborderw=18" % alpha
    args[0] += ":line_spacing=12"
    return args

def zoompan_expr(dur, direction="in"):
    frames = dur * FPS
    if direction == "in":
        z = "min(1.0+0.0015*on,1.18)"
    else:
        z = "max(1.18-0.0015*on,1.0)"
    return "zoompan=z='%s':x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)':d=%d:s=%dx%d:fps=%d" % (z, frames, W, H, FPS)

def scene_photo(idx, photo, dur, direction, overlay_lines, start_ts, total):
    """Render scene foto dgn zoompan + teks. Return file path."""
    fname = os.path.join(TMP, f"scene{idx}.mp4")
    img = os.path.join(ROOT, photo)
    # bg overlay (darken bawah utk teks)
    vf = [
        "scale=2160:3840:force_original_aspect_ratio=increase",
        "crop=2160:3840",
        zoompan_expr(dur, direction),
        "eq=brightness=-0.08:saturation=1.05",
        # vignette gelap di bawah
        "drawbox=x=0:y=ih*0.62:w=iw:h=ih*0.38:color=black@0.55:t=fill",
    ]
    # overlay teks: support 2 blok (atas-utama & bawah-CTA)
    txtfiles = []
    for i, (text, y_frac, size, color) in enumerate(overlay_lines):
        tf = write_text(f"t{idx}_{i}.txt", text)
        txtfiles.append(tf)
        y = int(H * y_frac)
        vf += drawtext_args(tf, y, size, color)
    cmd = ["ffmpeg", "-y", "-loop", "1", "-t", str(dur), "-i", img,
           "-filter_complex", ",".join(vf), "-t", str(dur),
           "-r", str(FPS), "-c:v", "libx264", "-preset", "medium", "-crf", "20",
           "-pix_fmt", "yuv420p", "-an", fname]
    r = subprocess.run(cmd, capture_output=True, text=True)
    if r.returncode != 0:
        print(f"scene{idx} FAIL:\n{r.stderr[-1500:]}")
        sys.exit(1)
    print(f"scene{idx} OK ({os.path.getsize(fname)//1024} KB)")
    return fname

def scene_text(idx, dur, lines_with_time):
    """Scene grafis (dark bg) dgn baris muncul bertahap."""
    fname = os.path.join(TMP, f"scene{idx}.mp4")
    vf = ["color=c=0x0B1220:s=%dx%d:r=%d" % (W, H, FPS), "format=yuv420p"]
    for i, (text, y_frac, size, color, t_start, t_end) in enumerate(lines_with_time):
        tf = write_text(f"t{idx}_{i}.txt", text)
        y = int(H * y_frac)
        d = drawtext_args(tf, y, size, color)[0]
        d += ":enable='between(t,%f,%f)'" % (t_start, t_end)
        vf.append(d)
    # garis aksen dekoratif
    cmd = ["ffmpeg", "-y", "-f", "lavfi", "-i", "color=c=0x0B1220:s=%dx%d:r=%d" % (W, H, FPS),
           "-filter_complex", ",".join(vf), "-t", str(dur),
           "-r", str(FPS), "-c:v", "libx264", "-preset", "medium", "-crf", "20",
           "-pix_fmt", "yuv420p", "-an", fname]
    r = subprocess.run(cmd, capture_output=True, text=True)
    if r.returncode != 0:
        print(f"scene{idx} FAIL:\n{r.stderr[-1200:]}")
        sys.exit(1)
    print(f"scene{idx} OK ({os.path.getsize(fname)//1024} KB)")
    return fname

# ── Scene 1: Hook (4s) ref_1 ──
s1 = scene_photo(1, "uky_ref_1.jpg", 4, "in", [
    ("50 AKUN MEDIA SOSIAL...", 0.30, 76, "white"),
    ("BUTUH 50 ADMIN?", 0.42, 76, "0xFDBA74"),
], 0, 30)

# ── Scene 2: Plot twist (5s) ref_3 ──
s2 = scene_photo(2, "uky_ref_3.jpg", 5, "out", [
    ("PLOT TWIST-NYA:", 0.32, 70, "0xFDBA74"),
    ("CUKUP 1 ORANG + AI", 0.44, 80, "white"),
], 4, 30)

# ── Scene 3: Bukti grafis (9s) ──
s3 = scene_text(3, 9, [
    ("INI YANG BISA AI HANDLE:", 0.28, 64, "0x93C5FD", 0, 9),
    ("Jadwal posting semua platform", 0.45, 58, "white", 1.0, 9),
    ("Balas mention otomatis", 0.55, 58, "white", 3.0, 9),
    ("Laporan performa tiap minggu", 0.65, 58, "white", 5.0, 9),
])

# ── Scene 4: Social proof (6s) ref_2 ──
s4 = scene_photo(4, "uky_ref_2.jpg", 6, "in", [
    ("INI YANG KAMI JALANIN", 0.30, 66, "white"),
    ("SETIAP HARI DI STUDIOSOFT", 0.42, 66, "0xFDBA74"),
], 13, 30)

# ── Scene 5: CTA (6s) ref_6 ──
s5 = scene_photo(5, "uky_ref_6.jpg", 6, "out", [
    ("Penasaran caranya?", 0.30, 68, "white"),
    ("Baca cerita lengkapnya:", 0.42, 54, "0x93C5FD"),
    ("studiosoft.id/kelola-banyak-akun-", 0.54, 40, "0xFDBA74"),
], 19, 30)

# ── concat ──
lst = os.path.join(TMP, "list.txt")
with open(lst, "w") as f:
    for p in [s1, s2, s3, s4, s5]:
        f.write(f"file '{p}'\n")
cmd = ["ffmpeg", "-y", "-f", "concat", "-safe", "0", "-i", lst,
       "-c:v", "libx264", "-preset", "medium", "-crf", "20", "-pix_fmt", "yuv420p",
       "-movflags", "+faststart", OUT]
r = subprocess.run(cmd, capture_output=True, text=True)
if r.returncode != 0:
    print("concat FAIL:\n", r.stderr[-1200:])
    sys.exit(1)
print("\nDONE:", OUT, os.path.getsize(OUT) // 1024, "KB")
