import os, json
import numpy as np, cv2
from PIL import Image, ImageDraw, ImageFont

A = "/var/aiadultvideo/output/aiadult/s04v7/"
MOTHER = A + "S04_s31.mp4"
FIXED = A + "mouthfix4/S04_s31_p3fix_acopy90.mp4"
OUT = A + "bangs_check/"
os.makedirs(OUT, exist_ok=True)

try:
    font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 14)
except Exception:
    font = None


def load(p):
    cap = cv2.VideoCapture(p)
    fr = []
    while True:
        ok, f = cap.read()
        if not ok:
            break
        fr.append(f)
    cap.release()
    return fr


mo = load(MOTHER)
fx = load(FIXED)
print("mother frames", len(mo), "fixed frames", len(fx), flush=True)

h, w = mo[0].shape[:2]
# issue #7 bbox (normalized) -> pixels
bx0 = int(0.4157 * w); bx1 = int((0.4157 + 0.2213) * w)
by0 = int(0.0117 * h); by1 = int((0.0117 + 0.4084) * h)
print("bangs box px", bx0, by0, bx1, by1, flush=True)


def jump(seq, i, region=None):
    a = seq[i - 1]; b = seq[i]
    if region is not None:
        a = a[region[1]:region[3], region[0]:region[2]]
        b = b[region[1]:region[3], region[0]:region[2]]
    d = np.abs(a.astype(np.float32) - b.astype(np.float32))
    return float(d.mean()), float(d.max())


rows = []
for i in range(1, min(len(mo), len(fx))):
    m_full = jump(mo, i)
    f_full = jump(fx, i)
    m_bang = jump(mo, i, (bx0, by0, bx1, by1))
    f_bang = jump(fx, i, (bx0, by0, bx1, by1))
    rows.append({"f": i, "sec": round(i / 24.0, 3),
                 "mother_full_mean": round(m_full[0], 3), "fixed_full_mean": round(f_full[0], 3),
                 "mother_bang_mean": round(m_bang[0], 3), "fixed_bang_mean": round(f_bang[0], 3),
                 "mother_bang_max": round(m_bang[1], 1), "fixed_bang_max": round(f_bang[1], 1)})

# print window 20-45
print("f sec | mother_bang | fixed_bang | mother_full | fixed_full", flush=True)
for r in rows:
    if 20 <= r["f"] <= 45:
        print("%02d %.3f | %7.3f | %7.3f | %7.3f | %7.3f" % (
            r["f"], r["sec"], r["mother_bang_mean"], r["fixed_bang_mean"],
            r["mother_full_mean"], r["fixed_full_mean"]), flush=True)

top_m = sorted(rows, key=lambda r: -r["mother_bang_mean"])[:5]
top_f = sorted(rows, key=lambda r: -r["fixed_bang_mean"])[:5]
print("TOP mother bangs jumps:", [(r["f"], r["sec"], r["mother_bang_mean"]) for r in top_m], flush=True)
print("TOP fixed bangs jumps:", [(r["f"], r["sec"], r["fixed_bang_mean"]) for r in top_f], flush=True)

# how much did the mouthfix change outside the bangs box / overall?
for i in (29, 30, 31, 32, 33):
    d = np.abs(mo[i].astype(np.float32) - fx[i].astype(np.float32))
    print("mouthfix-vs-mother f%02d mean %.3f max %.0f" % (i, float(d.mean()), float(d.max())), flush=True)

json.dump(rows, open(OUT + "bangs_jumps.json", "w"), indent=1)


def label(img, txt):
    im = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)).copy()
    dd = ImageDraw.Draw(im)
    dd.rectangle([0, 0, 150, 18], fill=(0, 0, 0))
    dd.text((3, 2), txt, fill=(255, 255, 0), font=font)
    return im


def strip_pair(idxs, name, tw=300, th=168):
    sh = Image.new("RGB", (len(idxs) * tw, 2 * th + 20), (10, 10, 10))
    dd = ImageDraw.Draw(sh)
    dd.text((4, 2), "TOP = mother (pre-mouthfix)   BOTTOM = mouthfix v8", fill=(255, 255, 0), font=font)
    for k, i in enumerate(idxs):
        for row, seq in enumerate([mo, fx]):
            c = cv2.resize(seq[i], (tw, th))
            sh.paste(label(c, "f%02d %.2fs" % (i, i / 24.0)), (k * tw, 20 + row * th))
    sh.save(OUT + name)
    print("SAVED", OUT + name, flush=True)


strip_pair(list(range(27, 36)), "pair_full_f27_f35.png")

# bangs zoom pair
zw = 300; zh = 200
sh = Image.new("RGB", (5 * zw, 2 * zh + 20), (10, 10, 10))
dd = ImageDraw.Draw(sh)
dd.text((4, 2), "TOP = mother   BOTTOM = mouthfix v8   (bangs region zoom)", fill=(255, 255, 0), font=font)
for k, i in enumerate([29, 30, 31, 32, 33]):
    for row, seq in enumerate([mo, fx]):
        crop = seq[i][by0:by1, bx0:bx1]
        c = cv2.resize(crop, (zw, zh), interpolation=cv2.INTER_CUBIC)
        sh.paste(label(c, "f%02d %.2fs" % (i, i / 24.0)), (k * zw, 20 + row * zh))
sh.save(OUT + "pair_bangs_zoom_f29_f33.png")
print("SAVED", OUT + "pair_bangs_zoom_f29_f33.png", flush=True)

# difference maps (fixed vs mother) at f30/f31
sh = Image.new("RGB", (3 * 300, 190), (10, 10, 10))
dd = ImageDraw.Draw(sh)
dd.text((4, 2), "|mouthfix - mother| diff map (white = changed)", fill=(255, 255, 0), font=font)
for k, i in enumerate([30, 31, 32]):
    d = np.abs(mo[i].astype(np.float32) - fx[i].astype(np.float32)).sum(2)
    dn = np.clip(d * 6, 0, 255).astype(np.uint8)
    c = cv2.resize(cv2.applyColorMap(dn, cv2.COLORMAP_INFERNO), (300, 168))
    sh.paste(label(c, "f%02d" % i), (k * 300, 20))
sh.save(OUT + "diffmap_f30_f32.png")
print("SAVED", OUT + "diffmap_f30_f32.png", flush=True)
print("BANGS_CHECK_DONE", flush=True)
