#!/usr/bin/env python3
"""Render Mode B — podcast animasi (foto + quote teks), 9:16, ±72 dtk."""
import subprocess, os, sys

ROOT = "/home/mantapman/.hermes/profiles/atun/workspace/uky_video_pilot"
OUT = os.path.join(ROOT, "modeB_podcast_seo.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, ".modeB_tmp")
os.makedirs(TMP, exist_ok=True)

def wt(name, content):
    p = os.path.join(TMP, name)
    open(p, "w").write(content)
    return p

def dt(txtfile, y, size, color, font=FONT, box=True):
    a = ["drawtext=textfile='%s':fontfile='%s':fontsize=%d:fontcolor=%s:x=(w-text_w)/2:y=%d"
         % (txtfile, font, size, color, y)]
    if box:
        a[0] += ":box=1:boxcolor=black@0.45:boxborderw=16"
    a[0] += ":line_spacing=10"
    return a

def zp(dur, direction):
    f = dur * FPS
    z = "min(1.0+0.0016*on,1.20)" if direction == "in" else "max(1.20-0.0016*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, f, W, H, FPS)

def photo_scene(idx, photo, dur, direction, layers):
    out = os.path.join(TMP, "s%d.mp4" % idx)
    vf = ["scale=2160:3840:force_original_aspect_ratio=increase", "crop=2160:3840",
          zp(dur, direction), "eq=brightness=-0.06:saturation=1.03",
          "drawbox=x=0:y=ih*0.60:w=iw:h=ih*0.40:color=black@0.52:t=fill"]
    for i, (txt, yf, sz, col, fnt) in enumerate(layers):
        tf = wt("t%d_%d.txt" % (idx, i), txt)
        vf += dt(tf, int(H * yf), sz, col, fnt)
    cmd = ["ffmpeg", "-y", "-loop", "1", "-t", str(dur), "-i", os.path.join(ROOT, photo),
           "-filter_complex", ",".join(vf), "-t", str(dur), "-r", str(FPS),
           "-c:v", "libx264", "-preset", "medium", "-crf", "20", "-pix_fmt", "yuv420p", "-an", out]
    r = subprocess.run(cmd, capture_output=True, text=True)
    if r.returncode:
        print("s%d FAIL" % idx, r.stderr[-900:]); sys.exit(1)
    print("scene%d OK (%d KB)" % (idx, os.path.getsize(out) // 1024))
    return out

def graphic_scene(idx, dur, items):
    out = os.path.join(TMP, "s%d.mp4" % idx)
    vf = ["color=c=0x0B1220:s=%dx%d:r=%d" % (W, H, FPS), "format=yuv420p"]
    # aksen garis kiri
    vf.append("drawbox=x=90:y=ih*0.20:w=12:h=ih*0.14:color=0xFDBA74:t=fill")
    for i, (txt, yf, sz, col, fnt, t0, t1) in enumerate(items):
        tf = wt("t%d_%d.txt" % (idx, i), txt)
        d = dt(tf, int(H * yf), sz, col, fnt)[0] + ":enable='between(t,%f,%f)'" % (t0, t1)
        vf.append(d)
    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", out]
    r = subprocess.run(cmd, capture_output=True, text=True)
    if r.returncode:
        print("s%d FAIL" % idx, r.stderr[-900:]); sys.exit(1)
    print("scene%d OK (%d KB)" % (idx, os.path.getsize(out) // 1024))
    return out

LT = "UKY YANU HANDOKO  •  FOUNDER STUDIOSOFT"
OR = "0xFDBA74"; BL = "0x93C5FD"; WH = "white"

# S1 Hook 0-8s
s1 = photo_scene(1, "uky_ref_1.jpg", 8, "in", [
    ("BANYAK YANG KIRA JASA SEO ITU KAYAK SULAP...", 0.30, 62, WH, FONT),
    ("PADAHLAH... NGGAK GITU.", 0.44, 66, OR, FONT),
    (LT, 0.86, 34, BL, FONT_REG),
])

# S2 Awal cerita 8-22s
s2 = photo_scene(2, "uky_ref_3.jpg", 14, "out", [
    ("CERITA AWAL STUDIOSOFT", 0.28, 44, BL, FONT_REG),
    ("WEBSITE DOANG", 0.40, 70, WH, FONT),
    ("NGGAK CUKUP.", 0.51, 70, OR, FONT),
    ("Orang harus bisa NEMUIN kamu dulu", 0.64, 46, WH, FONT_REG),
])

# S3 Kasus nyata (grafik) 22-45s
s3 = graphic_scene(3, 23, [
    ("KASUS NYATA: KLINIK SURABAYA", 0.22, 50, BL, FONT, 0, 23),
    ("5 -> 100+", 0.35, 96, OR, FONT, 1.5, 23),
    ("pengunjung website / bulan", 0.46, 40, WH, FONT_REG, 2.2, 23),
    ("Google Business dioptimasi", 0.58, 50, WH, FONT, 5.0, 23),
    ("Konten jawab yang orang cari", 0.67, 50, WH, FONT, 8.0, 23),
    ("Struktur website dirapihin", 0.76, 50, WH, FONT, 11.0, 23),
    ("BUKAN SULAP. SISTEM.", 0.88, 54, OR, FONT, 15.0, 23),
])

# S4 Pelajaran 45-58s
s4 = photo_scene(4, "uky_ref_2.jpg", 13, "in", [
    ("SEO ITU MARATON,", 0.32, 70, WH, FONT),
    ("BUKAN SPRINT.", 0.44, 70, OR, FONT),
    ("Konsisten  •  Relevan  •  Terukur", 0.62, 46, BL, FONT_REG),
])

# S5 CTA 58-72s
s5 = photo_scene(5, "uky_ref_6.jpg", 14, "out", [
    ("PENASARAN DENGAN CERITA LENGKAPNYA?", 0.26, 56, WH, FONT),
    ("AUDIT WEBSITE GRATIS", 0.42, 66, OR, FONT),
    ("studiosoft.id", 0.56, 56, BL, FONT),
    ("Klik link di bio / di bawah", 0.68, 38, WH, FONT_REG),
])

lst = os.path.join(TMP, "list.txt")
with open(lst, "w") as f:
    for p in [s1, s2, s3, s4, s5]:
        f.write("file '%s'\n" % p)
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:
    print("concat FAIL", r.stderr[-1000:]); sys.exit(1)
print("\nDONE:", OUT, os.path.getsize(OUT) // 1024, "KB")
