import json, time, urllib.request, os, hashlib, shutil, subprocess
import numpy as np, cv2
from scipy.io import wavfile
from PIL import Image, ImageDraw, ImageFont
from insightface.app import FaceAnalysis

BASE = "http://127.0.0.1:8189"
I = "/var/aiadultvideo/input/"
A = "/var/aiadultvideo/output/aiadult/"
OUT = A + "s07s08_ref/"
os.makedirs(OUT, exist_ok=True)
P = open(I + "s07v14_main.txt", encoding="utf-8").read().strip()
print("prompt_chars", len(P), "md5", hashlib.md5(P.encode()).hexdigest(),
      "scenetrans_count", P.count("<scenetrans>"), flush=True)

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


def post(p, b):
    req = urllib.request.Request(BASE + p, data=json.dumps(b).encode(),
                                 headers={"Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=300) as r:
        return json.loads(r.read().decode())


def wait(pid, timeout=5400):
    t0 = time.time()
    while time.time() - t0 < timeout:
        try:
            h = json.loads(urllib.request.urlopen(BASE + "/history/" + pid, timeout=30).read())
        except Exception:
            time.sleep(4); continue
        if pid in h:
            st = h[pid].get("status", {})
            if st.get("status_str") == "success":
                for k in h[pid]["outputs"]:
                    for v in h[pid]["outputs"][k].get("videos", []) + h[pid]["outputs"][k].get("images", []):
                        fn = v.get("filename")
                        if fn:
                            cand = os.path.join("/var/aiadultvideo/output", v.get("subfolder") or "", fn)
                            if os.path.exists(cand):
                                return cand, time.time() - t0, h[pid]["outputs"]
                return None, time.time() - t0, h[pid]["outputs"]
            if st.get("status_str") == "error":
                print("ERR", json.dumps(st)[:600], flush=True)
                return None, time.time() - t0, None
        time.sleep(4)
    return None, time.time() - t0, None


def graph(p, seed, length=175, steps=8):
    return {
     "1": {"class_type": "UNETLoader", "inputs": {"unet_name": "minimax_h3_ref2va_pruned_fp8_scaled.safetensors", "weight_dtype": "default"}},
     "2": {"class_type": "CLIPLoader", "inputs": {"clip_name": "qwen3vl_32b_heretic_minimax_h3_nvfp4.safetensors", "type": "minimax", "device": "default"}},
     "3": {"class_type": "VAELoader", "inputs": {"vae_name": "minimax_h3_video_vae_fp16.safetensors"}},
     "4": {"class_type": "VAELoader", "inputs": {"vae_name": "minimax_h3_audio_vae_fp32.safetensors"}},
     "5": {"class_type": "LoraLoaderModelOnly", "inputs": {"model": ["1", 0], "lora_name": "pika_h3_flex_turbo_8step_hd_ref2va.safetensors", "strength_model": 1.0}},
     "6": {"class_type": "MiniMaxH3SigmaShift", "inputs": {"model": ["5", 0], "shift_video": 12.0, "shift_audio": 3.0}},
     "7": {"class_type": "LoadImage", "inputs": {"image": "S07_ref_media60.png"}},
     "17": {"class_type": "LoadImage", "inputs": {"image": "S08_ref_media58.png"}},
     "18": {"class_type": "LoadAudio", "inputs": {"audio": "ref_S03_female.wav"}},
     "8": {"class_type": "MiniMaxH3ReferenceToVideo", "inputs": {
        "clip": ["2", 0], "prompt": p, "width": 1312, "height": 736, "length": length,
        "ref_image_size": "match", "vae": ["3", 0], "audio_vae": ["4", 0],
        "ref_images.ref_image_0": ["7", 0],
        "ref_images.ref_image_1": ["17", 0],
        "ref_audios.ref_audio_0": ["18", 0]}},
     "9": {"class_type": "MiniMaxH3AddGuide", "inputs": {"positive": ["8", 0], "latent": ["8", 1], "frame_idx": 0, "vae": ["3", 0], "image": ["7", 0]}},
     "16": {"class_type": "MiniMaxH3TokenCounter", "inputs": {"samples": ["8", 1], "conditioning": ["9", 0]}},
     "10": {"class_type": "ConditioningZeroOut", "inputs": {"conditioning": ["9", 0]}},
     "11": {"class_type": "KSampler", "inputs": {"model": ["6", 0], "seed": seed, "steps": steps, "cfg": 1.0, "sampler_name": "res_multistep", "scheduler": "simple", "positive": ["9", 0], "negative": ["10", 0], "latent_image": ["8", 1], "denoise": 1.0}},
     "12": {"class_type": "VAEDecode", "inputs": {"samples": ["11", 0], "vae": ["3", 0]}},
     "13": {"class_type": "VAEDecodeAudio", "inputs": {"samples": ["11", 0], "vae": ["4", 0]}},
     "14": {"class_type": "CreateVideo", "inputs": {"images": ["12", 0], "fps": 24.0, "audio": ["13", 0]}},
     "15": {"class_type": "SaveVideo", "inputs": {"video": ["14", 0], "filename_prefix": "aiadult/s07s08_ref/S07S08_ref_s%d" % seed, "format": "auto", "codec": "auto"}},
    }


res = {}
seed = 31
r = post("/prompt", {"prompt": graph(P, seed)})
pid = r.get("prompt_id")
print("prompt_id", pid, json.dumps(r)[:300], flush=True)
if not pid:
    raise SystemExit(1)
src, wall, outputs = wait(pid)
print("wall %.0f" % wall, "src", src, flush=True)
if not src:
    raise SystemExit(1)
dst = OUT + "S07S08_ref_s%d.mp4" % seed
shutil.copyfile(src, dst)
res["prompt_id"] = pid; res["wall"] = round(wall); res["src"] = dst
res["prompt_md5"] = hashlib.md5(P.encode()).hexdigest()
res["ref_audio"] = "ref_S03_female.wav"
if outputs:
    for k, v in outputs.items():
        if "text" in v:
            print("NODE", k, json.dumps(v["text"], ensure_ascii=False)[:600], flush=True)
            res.setdefault("token_breakdown", []).append(v["text"])

# ---- measure ----
cap = cv2.VideoCapture(dst); fr = []
while True:
    ok, f = cap.read()
    if not ok: break
    fr.append(f)
cap.release(); N = len(fr)
res["frames"] = N
d = [float(np.abs(fr[i].astype(np.float32) - fr[i - 1].astype(np.float32)).mean()) for i in range(1, N)]
res["max_jump"] = round(max(d), 2); res["max_jump_frame"] = int(np.argmax(d)) + 1
res["max_jump_sec"] = round(res["max_jump_frame"] / 24.0, 3)
res["top_jumps"] = [(i + 1, round(d[i], 2)) for i in np.argsort(d)[::-1][:6]]
faces = [len(app.get(fr[i])) for i in range(0, N, 4)]
res["max_faces"] = max(faces)
res["face_missing"] = sum(1 for i in range(0, N, 4) if faces[i // 4] == 0)
lum = [float(f.astype(np.float32).mean()) for f in fr]
res["lum"] = [round(lum[0]), round(min(lum)), round(lum[-1])]

# audio
wav = OUT + "S07S08_ref_s%d.wav" % seed
subprocess.run(["ffmpeg", "-y", "-v", "error", "-i", dst, "-vn", "-ac", "1", "-ar", "16000", "-c:a", "pcm_s16le", wav], check=True)
sr, x = wavfile.read(wav)
SR = 16000
fl, hop = 640, 160
n = 1 + (len(x) - fl) // hop
frames = np.stack([x[i * hop:i * hop + fl] for i in range(n)])
db = 20 * np.log10(np.sqrt((frames.astype(np.float64) ** 2).mean(1) + 1e-12) / 32768.0)
noise = float(np.percentile(db, 10)); peak = float(np.percentile(db, 99))
thr = max(noise + 10.0, peak - 25.0)
v = db > thr
# speech segments
segs = []; i = 0
while i < n:
    if not v[i]: i += 1; continue
    j = i
    while j + 1 < n and v[j + 1]: j += 1
    segs.append((round(i * 0.01, 2), round(j * 0.01, 2))); i = j + 1
merged = []
for s in segs:
    if merged and s[0] - merged[-1][1] <= 0.35: merged[-1] = (merged[-1][0], s[1])
    else: merged.append(s)
res["speech_segments_sec"] = merged
res["voiced_sec"] = round(float(v.sum()) * 0.01, 2)
res["noise_db"] = round(noise, 1); res["peak_db"] = round(peak, 1)


def yin(fr_):
    out = np.full(len(fr_), np.nan); tmin, tmax = 40, 267
    for i2, f in enumerate(fr_):
        f = f.astype(np.float64); f = f - f.mean()
        if np.sum(f ** 2) < 1e-6: continue
        dd = np.full(tmax + 1, np.nan)
        for tau in range(tmin, tmax + 1):
            dd[tau] = np.sum((f[:len(f) - tau] - f[tau:]) ** 2)
        cm = np.ones(tmax + 1); run = 0.0
        for tau in range(1, tmax + 1):
            run += dd[tau] if not np.isnan(dd[tau]) else 0.0
            if run > 0: cm[tau] = dd[tau] * tau / run
        best = None
        for tau in range(tmin, tmax + 1):
            if cm[tau] < 0.18 and tau + 1 <= tmax and cm[tau] <= cm[tau + 1]:
                best = tau; break
        if best is None:
            seg = cm[tmin:tmax + 1]; j2 = int(np.nanargmin(seg))
            if seg[j2] < 0.35: best = tmin + j2
        if best: out[i2] = SR / best
    return out


f0 = yin(frames)
ok = v & ~np.isnan(f0) & (f0 > 60) & (f0 < 400)
vv = f0[ok]
res["f0_median"] = round(float(np.median(vv)), 1) if len(vv) > 5 else None
res["f0_p10"] = round(float(np.percentile(vv, 10)), 1) if len(vv) > 5 else None
res["f0_p90"] = round(float(np.percentile(vv, 90)), 1) if len(vv) > 5 else None
res["f0_count"] = int(len(vv))
# F0 per window
def win_f0(a, b):
    m = np.zeros(len(f0), bool); m[int(a * 100):int(b * 100)] = True
    sel = f0[m & ok]
    return round(float(np.median(sel)), 1) if len(sel) > 5 else None
res["f0_by_window"] = {"0-2.6": win_f0(0, 2.6), "2.6-4.4": win_f0(2.6, 4.4), "4.4-4.6": win_f0(4.4, 4.6), "4.6-7.0": win_f0(4.6, 7.0)}

# ---- split at measured cut ----
cut = res["max_jump_frame"]
res["cut_frame"] = cut
pre = OUT + "S07_ref_s%d.mp4" % seed
postv = OUT + "S08_ref_s%d.mp4" % seed
subprocess.run(["ffmpeg", "-y", "-v", "error", "-i", dst, "-frames:v", str(cut), "-c:v", "libx264", "-crf", "16", "-preset", "medium", "-pix_fmt", "yuv420p", "-c:a", "copy", pre], check=False)
subprocess.run(["ffmpeg", "-y", "-v", "error", "-i", dst, "-vf", "select=gte(n\\,%d)" % cut, "-vsync", "0", "-c:v", "libx264", "-crf", "16", "-preset", "medium", "-pix_fmt", "yuv420p", "-c:a", "copy", postv], check=False)
res["split_pre"] = pre; res["split_post"] = postv
for f in (pre, postv):
    pr = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries",
                         "stream=nb_frames,duration", "-of", "csv=p=0", f], capture_output=True, text=True)
    print(f, pr.stdout.strip(), flush=True)

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


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(fr[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, N, 8)), "sheet_S07S08_ref_s%d.png" % seed)
strip(list(range(max(0, cut - 8), min(N, cut + 8))), "cut_S07S08_ref_s%d.png" % seed)
json.dump(res, open(OUT + "s07s08_ref.json", "w"), ensure_ascii=False, indent=1)
print("MEASURE", json.dumps(res, ensure_ascii=False), flush=True)
print("S07S08_REF_DONE", flush=True)
