#!/usr/bin/env python3
"""Zoom recording guide test. Builds a made-up meeting-style recording (slides + moving camera tile + synthetic speech),
then measures: audio extract with stream copy (and its failure case), size/quality of shrink options.
Usage: python3 zoom_test.py <workdir>. Needs ffmpeg/ffprobe with libx264, drawtext, ssim; espeak-ng."""
import subprocess, sys, os, json, re
W = sys.argv[1]; os.makedirs(W, exist_ok=True); os.chdir(W)
FONT = "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"
BOLD = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
def run(cmd, check=True):
    r = subprocess.run(cmd, shell=True, capture_output=True, text=True)
    if check and r.returncode: print("CMD FAILED:", cmd, r.stderr[-600:]); sys.exit(1)
    return r
def probe(f, what):
    return run(f"ffprobe -v error {what} -of json {f}").stdout
def dur(f): return float(json.loads(probe(f, "-show_entries format=duration"))["format"]["duration"])
def size(f): return os.path.getsize(f)
def kb(n): return f"{n/1024:.0f} KB"

SCRIPT = ("Welcome to the packaging review. Today we compare three box designs for the spring order. "
 "First, the current design. It ships flat, assembles in ten seconds, and has the lowest cost per unit. "
 "Second, the new fold lock design. It holds more weight, but it needs a longer assembly step. "
 "Third, the rigid box. It looks best on a shelf, and it costs the most to ship. "
 "On the next slide you can see the damage rate from the last two shipments. "
 "The fold lock design had the fewest damaged boxes in both tests. "
 "The rigid box had no damage, but it is heavier. "
 "Now the costs. Shipping weight drives most of the difference, so we priced each design by weight and not by size. "
 "The table shows the result for one hundred boxes. "
 "My recommendation is the fold lock design for the spring order, and a small trial of the rigid box for gift sets. "
 "Please send questions to the team channel before Friday. Thank you for joining the review.")
open("script.txt","w").write(SCRIPT)
run("espeak-ng -v en-us -s 150 -w narration.wav -f script.txt")
D = dur("narration.wav"); N = 6; SL = D/N
print(f"NARRATION {D:.3f} s, {N} slides of {SL:.3f} s")
titles = ["Packaging review","Three designs","Damage rate","Cost per 100 boxes","Recommendation","Questions"]
bullets = [["Spring order","Box designs compared","Review for the team"],
 ["Current: flat, 10 s to assemble","Fold lock: stronger, slower","Rigid: best look, heaviest"],
 ["Fold lock: fewest damaged","Rigid: none damaged","Current: most damaged"],
 ["Priced by shipping weight","Current: lowest total","Rigid: highest total"],
 ["Fold lock for the spring order","Rigid trial for gift sets","Decide by Friday"],
 ["Send questions to the team channel","Thank you"]]
for i in range(N):
    open(f"b{i}.txt","w").write("\n".join(bullets[i]))
    bars = "".join(f",drawbox=x={200+k*140}:y={900-h}:w=100:h={h}:color=0x2a6fdb@1:t=fill" for k,h in enumerate([120+40*((i+k)%4)*1 for k in range(5)])) if i in (2,3) else ""
    vf = (f"drawtext=fontfile={BOLD}:text='{titles[i]}':fontsize=96:fontcolor=black:x=120:y=80,"
          f"drawtext=fontfile={FONT}:textfile=b{i}.txt:fontsize=56:line_spacing=28:fontcolor=0x222222:x=120:y=260{bars}")
    run(f"ffmpeg -y -v error -f lavfi -i color=c=white:s=1920x1080:r=25:d={SL:.3f} -f lavfi -i testsrc2=s=320x180:r=25:d={SL:.3f} "
        f"-filter_complex \"[0:v]{vf}[a];[a][1:v]overlay=x=1560:y=40[v]\" -map '[v]' -c:v libx264 -crf 12 -pix_fmt yuv420p s{i}.mp4")
open("list.txt","w").write("".join(f"file s{i}.mp4\n" for i in range(N)))
run("ffmpeg -y -v error -f concat -i list.txt -c copy video_only.mp4")
run("ffmpeg -y -v error -i video_only.mp4 -i narration.wav -c:v libx264 -crf 18 -preset medium -pix_fmt yuv420p -c:a aac -b:a 128k -shortest source.mp4")
S = size("source.mp4")
print("\n## SOURCE (made-up meeting-style recording)")
print(run("ffprobe -v error -show_entries stream=codec_type,codec_name,width,height,r_frame_rate,bit_rate,channels,sample_rate -show_entries format=duration,size -of compact=p=0 source.mp4").stdout.strip())
print(f"source size {S} bytes = {kb(S)}, duration {dur('source.mp4'):.3f} s")

def ssim(f):
    r = run(f"ffmpeg -v error -i {f} -i source.mp4 -filter_complex \"[0:v]scale=1920:1080:flags=bicubic,fps=25[a];[1:v]fps=25[b];[a][b]ssim\" -f null - 2>&1", check=False)
    r2 = subprocess.run(f"ffmpeg -i {f} -i source.mp4 -filter_complex \"[0:v]scale=1920:1080:flags=bicubic,fps=25[a];[1:v]fps=25[b];[a][b]ssim\" -f null - 2>&1 | grep 'SSIM Y'", shell=True, capture_output=True, text=True).stdout
    m = re.search(r"All:([0-9.]+)", r2); return float(m.group(1)) if m else None
print("\n## CONTROL: SSIM of the source against itself must be 1.000000")
c = ssim("source.mp4"); print(f"SSIM source vs source = {c}  {'PASS' if c and c>0.9999 else 'FAIL'}")

print("\n## AUDIO ONLY: extract with stream copy")
run("ffmpeg -y -v error -i source.mp4 -vn -c:a copy audio_only.m4a")
print(run("ffprobe -v error -show_entries stream=codec_name,bit_rate -show_entries format=duration,size -of compact=p=0 audio_only.m4a").stdout.strip())
print(f"audio_only.m4a {size('audio_only.m4a')} bytes = {kb(size('audio_only.m4a'))} of source {kb(S)}: {100*size('audio_only.m4a')/S:.1f}% ; duration {dur('audio_only.m4a'):.3f} s (control: source {dur('source.mp4'):.3f} s)")
print("\n## FAILURE CASE: same command when the audio is not AAC (PCM in a MKV)")
run("ffmpeg -y -v error -i source.mp4 -c:v copy -c:a pcm_s16le pcm.mkv")
r = run("ffmpeg -y -i pcm.mkv -vn -c:a copy pcm_audio.m4a", check=False)
print("exit code", r.returncode); print("\n".join(l.strip() for l in r.stderr.splitlines() if re.search(r"Could not|Error|Invalid|tag", l) and "configuration" not in l)[:700])
print("ffprobe audio codec of pcm.mkv:", run("ffprobe -v error -select_streams a -show_entries stream=codec_name -of csv=p=0 pcm.mkv").stdout.strip())

print("\n## SHRINK OPTIONS (x264 preset medium, audio AAC)")
opts = [("1080p CRF 18 (source settings, control)","-c:v libx264 -crf 18","128k"),
 ("1080p CRF 23","-c:v libx264 -crf 23","128k"),("1080p CRF 28","-c:v libx264 -crf 28","128k"),
 ("1080p CRF 32","-c:v libx264 -crf 32","128k"),("1080p CRF 51 (control: must be worst)","-c:v libx264 -crf 51","128k"),
 ("720p CRF 28","-vf scale=-2:720 -c:v libx264 -crf 28","128k"),("540p CRF 28","-vf scale=-2:540 -c:v libx264 -crf 28","128k"),
 ("720p CRF 28, 10 fps","-vf scale=-2:720,fps=10 -c:v libx264 -crf 28","128k"),
 ("720p CRF 28, 10 fps, audio 48k mono","-vf scale=-2:720,fps=10 -c:v libx264 -crf 28 -ac 1","48k")]
res = []
for i,(name,args,ab) in enumerate(opts):
    f = f"o{i}.mp4"
    run(f"ffmpeg -y -v error -i source.mp4 {args} -pix_fmt yuv420p -c:a aac -b:a {ab} {f}")
    sz = size(f); q = ssim(f); res.append((name,sz,q,dur(f)))
    print(f"{name} | {sz} bytes | {kb(sz)} | {100*sz/S:.1f}% of source | SSIM {q} | {dur(f):.3f} s")
crf = {r[0]:r[2] for r in res}
ok = crf["1080p CRF 51 (control: must be worst)"] < min(v for k,v in crf.items() if "51" not in k)
print("CONTROL CRF 51 has the lowest SSIM:", "PASS" if ok else "FAIL")
json.dump({"source":S,"narration":D,"res":res}, open("results.json","w"))
