import os, subprocess
import numpy as np, cv2
from PIL import Image, ImageDraw, ImageFont
from insightface.app import FaceAnalysis

A = "/var/aiadultvideo/output/aiadult/s04v7/"
P3 = A + "p3_src.png"
OUT = A + "mouthfix2/"
os.makedirs(OUT, exist_ok=True)

app = FaceAnalysis(name="buffalo_l", providers=["CPUExecutionProvider"])
app.prepare(ctx_id=-1, det_size=(1280, 1280))


def mouth_box(face, h, w, wmul=1.30, hmul=0.24):
    kps = face.kps
    lm = kps[3]; rm = kps[4]
    b = [float(v) for v in face.bbox]
    fh = b[3] - b[1]
    mx = (lm[0] + rm[0]) / 2.0
    my = (lm[1] + rm[1]) / 2.0 + 0.02 * fh
    bw = max(16.0, abs(rm[0] - lm[0]) * wmul)
    bh = max(10.0, fh * hmul)
    x0 = int(max(0, mx - bw / 2)); x1 = int(min(w, mx + bw / 2))
    y0 = int(max(0, my - bh / 2)); y1 = int(min(h, my + bh / 2))
    return x0, y0, x1, y1


def feather_mask(w, h, pad=0.25):
    m = np.zeros((h, w), np.float32)
    cv2.ellipse(m, (w // 2, h // 2), (int(w * 0.5), int(h * 0.5)), 0, 0, 360, 1.0, -1)
    m = cv2.GaussianBlur(m, (0, 0), max(2, int(w * pad)))
    return m


def cavity_score(img, box, face_bbox):
    x0, y0, x1, y1 = box
    g = cv2.cvtColor(img[y0:y1, x0:x1], cv2.COLOR_BGR2GRAY).astype(np.float32)
    fb = [int(v) for v in face_bbox]
    fg = cv2.cvtColor(img[max(0, fb[1]):fb[3], max(0, fb[0]):fb[2]], cv2.COLOR_BGR2GRAY).astype(np.float32)
    med = float(np.median(fg))
    thr = med * 0.55
    return float((g < thr).sum()) / float(g.size)


def pick_face(img):
    fcs = app.get(img)
    if not fcs:
        return None
    return max(fcs, key=lambda q: (q.bbox[2] - q.bbox[0]) * (q.bbox[3] - q.bbox[1]))


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

# ---------- 1. source check: p3 ----------
p3 = cv2.imread(P3)
ph, pw = p3.shape[:2]
f3 = pick_face(p3)
if f3 is None:
    print("NO FACE IN P3", flush=True)
    raise SystemExit(1)
p3box = mouth_box(f3, ph, pw)
print("p3 size", pw, ph, "face_bbox", [round(float(v), 1) for v in f3.bbox], "mouth_box", p3box, flush=True)
p3cav = cavity_score(p3, p3box, f3.bbox)
print("p3 cavity_score", round(p3cav, 4), flush=True)
# p3 mouth zoom (3x) for reviewer source check
zx0 = int(max(0, p3box[0] - (p3box[2] - p3box[0]) * 0.4))
zx1 = int(min(pw, p3box[2] + (p3box[2] - p3box[0]) * 0.4))
zy0 = int(max(0, p3box[1] - (p3box[3] - p3box[1]) * 0.8))
zy1 = int(min(ph, p3box[3] + (p3box[3] - p3box[1]) * 0.8))
zoom = p3[zy0:zy1, zx0:zx1]
zoom = cv2.resize(zoom, (zoom.shape[1] * 3, zoom.shape[0] * 3), interpolation=cv2.INTER_CUBIC)
cv2.imwrite(OUT + "p3_src_mouth3x.png", zoom)
print("SAVED p3_src_mouth3x", flush=True)

patch = p3[p3box[1]:p3box[3], p3box[0]:p3box[2]].copy()
patch_h, patch_w = patch.shape[:2]
print("p3 mouth patch", patch_w, patch_h, flush=True)


def fix(tag):
    src = A + tag + ".mp4"
    cap = cv2.VideoCapture(src)
    fr = []
    while True:
        ok, f = cap.read()
        if not ok:
            break
        fr.append(f)
    cap.release()
    N = len(fr); h, w = fr[0].shape[:2]
    print(tag, "frames", N, w, h, flush=True)
    boxes = []; faces = []
    for f in fr:
        z = pick_face(f)
        faces.append(z)
        boxes.append(None if z is None else mouth_box(z, h, w))
    miss = sum(1 for b in boxes if b is None)
    cav_before = [cavity_score(fr[i], boxes[i], faces[i].bbox) for i in range(N) if boxes[i] is not None]
    print(tag, "face_missing", miss, "cavity_before mean", round(float(np.mean(cav_before)), 4), flush=True)

    out = []
    for i, f in enumerate(fr):
        b = boxes[i]
        if b is None:
            out.append(f); continue
        x0, y0, x1, y1 = b
        bw = x1 - x0; bh = y1 - y0
        if bw < 6 or bh < 6:
            out.append(f); continue
        ps = cv2.resize(patch, (bw, bh), interpolation=cv2.INTER_CUBIC)
        alpha = feather_mask(bw, bh)[:, :, None]
        roi = f[y0:y1, x0:x1].astype(np.float32)
        blend = ps.astype(np.float32) * alpha + roi * (1 - alpha)
        g = f.copy()
        g[y0:y1, x0:x1] = np.clip(blend, 0, 255).astype(np.uint8)
        out.append(g)

    cav_after = [cavity_score(out[i], boxes[i], faces[i].bbox) for i in range(N) if boxes[i] is not None]
    print(tag, "cavity_after mean", round(float(np.mean(cav_after)), 4), flush=True)

    dst = OUT + tag + "_p3fix.mp4"
    tmp = OUT + tag + "_tmp.mp4"
    vw = cv2.VideoWriter(tmp, cv2.VideoWriter_fourcc(*"mp4v"), 24.0, (w, h))
    for g in out:
        vw.write(g)
    vw.release()
    subprocess.run(["ffmpeg", "-y", "-v", "error", "-i", tmp, "-i", src,
                    "-map", "0:v:0", "-map", "1:a:0", "-c:v", "libx264", "-crf", "16",
                    "-preset", "medium", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "192k",
                    "-shortest", dst], check=True)
    os.remove(tmp)
    print("SAVED", dst, flush=True)

    # mouth motion after
    mm = []
    for i, g in enumerate(out):
        if boxes[i] is None:
            mm.append(None); continue
        x0, y0, x1, y1 = boxes[i]
        mm.append(cv2.resize(g[y0:y1, x0:x1], (64, 32)).astype(np.float32))
    mot = [None]
    for i in range(1, len(mm)):
        if mm[i] is None or mm[i - 1] is None:
            mot.append(None); continue
        mot.append(round(float(np.abs(mm[i] - mm[i - 1]).mean()), 2))
    mv = [x for x in mot if x is not None]
    print(tag, "mouth_motion_after mean", round(float(np.mean(mv)), 2), "max", max(mv), flush=True)

    def strip(idxs, name, cols=6, tw=300, th=168):
        rows = (len(idxs) + cols - 1) // cols
        sh = Image.new("RGB", (cols * tw, rows * th), (10, 10, 10)); dd = ImageDraw.Draw(sh)
        for k, i in enumerate(idxs):
            if i >= N:
                continue
            xx = (k % cols) * tw; yy = (k // cols) * th
            sh.paste(Image.fromarray(cv2.cvtColor(cv2.resize(out[i], (tw, th)), cv2.COLOR_BGR2RGB)), (xx, yy))
            dd.text((xx + 3, yy + 3), "f%03d %.2fs" % (i, i / 24.0), fill=(255, 255, 0), font=font)
        sh.save(OUT + name); print("SAVED", OUT + name, flush=True)

    strip(list(range(0, 30)), tag + "_p3fix_0_1p25s.png")
    strip(list(range(30, 60)), tag + "_p3fix_1p25_2p5s.png")
    strip(list(range(60, N)), tag + "_p3fix_2p5_end.png")
    strip(list(range(0, N, 6)), tag + "_p3fix_sheet.png")

    # QC zoom: f36 f48 f89, before vs after, 3x
    qc_idx = [36, 48, 89]
    tw, th = 260, 150
    sh = Image.new("RGB", (len(qc_idx) * 2 * tw, 2 * th + 24), (10, 10, 10)); dd = ImageDraw.Draw(sh)
    dd.text((4, 2), "top=ORIGINAL  bottom=p3-mouthfix  (3x mouth zoom)", fill=(255, 255, 0), font=font)
    for k, i in enumerate(qc_idx):
        if i >= N or boxes[i] is None:
            continue
        x0, y0, x1, y1 = boxes[i]
        bw = x1 - x0; bh = y1 - y0
        ex = int(bw * 0.45); ey = int(bh * 0.9)
        cx0 = max(0, x0 - ex); cx1 = min(w, x1 + ex)
        cy0 = max(0, y0 - ey); cy1 = min(h, y1 + ey)
        for row, img in enumerate([fr[i], out[i]]):
            c = cv2.resize(img[cy0:cy1, cx0:cx1], (tw, th), interpolation=cv2.INTER_CUBIC)
            sh.paste(Image.fromarray(cv2.cvtColor(c, cv2.COLOR_BGR2RGB)), (k * 2 * tw + row * tw, 24))
            dd.text((k * 2 * tw + row * tw + 3, 24 + 2), "f%03d %s" % (i, "orig" if row == 0 else "p3fix"), fill=(255, 255, 0), font=font)
    sh.save(OUT + "qc_" + tag + "_f36_f48_f89.png")
    print("SAVED", OUT + "qc_" + tag + "_f36_f48_f89.png", flush=True)


for tag in ("S04_s31", "S04_s2026"):
    fix(tag)
print("P3MOUTHFIX_DONE", flush=True)
