import os, subprocess, json
import numpy as np
from scipy.io import wavfile

A = "/var/aiadultvideo/output/aiadult/ep01_delivery/"
OUT = "/var/aiadultvideo/output/aiadult/voice_ref/"
os.makedirs(OUT, exist_ok=True)
SR = 16000

SHOTS = [
    ("S01_v15", "male", "是不是連妳也不能接受我，妳也要拋棄我嗎？"),
    ("S02_v3", "male", "妳好。"),
    ("S03_v17", "female", "您好，歡迎光臨。／我們這裡的手工巧克力採取客製化挑選的方式。"),
    ("S04_v8", "female", "好高……（內心聲）"),
    ("S05_v18", "male", "聽起來都很棒……／有不含酒精的嗎？／我女朋友不太喜歡苦味。"),
    ("S06_v24", "female", "有的，這邊幾款都是無酒精、口味偏溫和的選擇。"),
    ("S06b_v5", "male", "好的，謝謝。"),
    ("S07_v15", "female", "這小小的舉動，（內心聲）"),
    ("S08_v27", "female", "讓我莫名的心跳微微加速（內心聲）"),
]


def to_wav(mp4, dst):
    subprocess.run(["ffmpeg", "-y", "-v", "error", "-i", mp4, "-vn", "-ac", "1",
                    "-ar", str(SR), "-c:a", "pcm_s16le", dst], check=True)


def frames(x, fl=640, hop=160):
    n = 1 + (len(x) - fl) // hop
    return np.stack([x[i * hop:i * hop + fl] for i in range(n)])


def rms_db(fr):
    r = np.sqrt((fr.astype(np.float64) ** 2).mean(1) + 1e-12)
    return 20 * np.log10(r / 32768.0)


def yin_f0(fr):
    out = np.full(len(fr), np.nan)
    tmin, tmax = 40, 267  # 400Hz..60Hz
    for i, f in enumerate(fr):
        f = f.astype(np.float64)
        f = f - f.mean()
        e = np.sum(f ** 2)
        if e < 1e-6:
            continue
        d = np.full(tmax + 1, np.nan)
        for tau in range(tmin, tmax + 1):
            d[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 += d[tau] if not np.isnan(d[tau]) else 0.0
            if run > 0:
                cm[tau] = d[tau] * tau / run
        best = None
        for tau in range(tmin, tmax + 1):
            if cm[tau] < 0.18:
                if tau + 1 <= tmax and cm[tau] <= cm[tau + 1]:
                    best = tau
                    break
        if best is None:
            seg = cm[tmin:tmax + 1]
            j = int(np.nanargmin(seg))
            if seg[j] < 0.35:
                best = tmin + j
        if best:
            out[i] = SR / best
    return out


results = []
for tag, spk, line in SHOTS:
    mp4 = A + tag + ".mp4"
    wav = OUT + tag + ".wav"
    to_wav(mp4, wav)
    sr, x = wavfile.read(wav)
    assert sr == SR
    fr = frames(x)
    db = rms_db(fr)
    noise = float(np.percentile(db, 10))
    peak = float(np.percentile(db, 99))
    thr = max(noise + 10.0, peak - 25.0)
    voiced = db > thr
    f0 = yin_f0(fr)
    ok = voiced & ~np.isnan(f0) & (f0 > 60) & (f0 < 400)
    v = f0[ok]
    dur_voiced = float(ok.sum()) * 0.01
    if len(v) > 5:
        res = {
            "shot": tag, "speaker": spk, "line": line,
            "noise_db": round(noise, 1), "peak_db": round(peak, 1), "thr_db": round(thr, 1),
            "voiced_sec": round(dur_voiced, 2),
            "f0_median": round(float(np.median(v)), 1),
            "f0_p10": round(float(np.percentile(v, 10)), 1),
            "f0_p90": round(float(np.percentile(v, 90)), 1),
            "f0_count": int(len(v)),
        }
    else:
        res = {"shot": tag, "speaker": spk, "line": line, "voiced_sec": round(dur_voiced, 2),
               "f0_median": None, "f0_p10": None, "f0_p90": None, "f0_count": int(len(v))}
    results.append(res)
    print(json.dumps(res, ensure_ascii=False), flush=True)

json.dump(results, open(OUT + "f0_ep01.json", "w"), ensure_ascii=False, indent=1)

# ---------- reference candidates: trim + concat within the SAME shot only ----------
def build_ref(tag, name, gap_merge=0.35, pad=0.15):
    wav = OUT + tag + ".wav"
    sr, x = wavfile.read(wav)
    fr = frames(x)
    db = rms_db(fr)
    noise = float(np.percentile(db, 10))
    peak = float(np.percentile(db, 99))
    thr = max(noise + 10.0, peak - 25.0)
    v = db > thr
    segs = []
    i = 0
    n = len(v)
    while i < n:
        if not v[i]:
            i += 1; continue
        j = i
        while j + 1 < n and v[j + 1]:
            j += 1
        segs.append([i, j]); i = j + 1
    merged = []
    for s in segs:
        if merged and (s[0] - merged[-1][1]) * 0.01 <= gap_merge:
            merged[-1][1] = s[1]
        else:
            merged.append(s)
    pieces = []
    for s in merged:
        a = max(0, int(s[0] * 160 - pad * SR))
        b = min(len(x), int(s[1] * 160 + 640 + pad * SR))
        if (b - a) > 0.12 * SR:
            pieces.append(x[a:b])
    if not pieces:
        print("no voice", tag, flush=True); return None
    y = np.concatenate(pieces)
    dst = OUT + name
    wavfile.write(dst, SR, y.astype(np.int16))
    # measure
    fr2 = frames(y)
    db2 = rms_db(fr2)
    f02 = yin_f0(fr2)
    ok2 = (db2 > thr) & ~np.isnan(f02) & (f02 > 60) & (f02 < 400)
    vv = f02[ok2]
    info = {"file": dst, "src_shot": tag, "seconds": round(len(y) / SR, 2),
            "segments": len(pieces), "rms_dbfs": round(float(20 * np.log10(np.sqrt((y.astype(np.float64) ** 2).mean()) / 32768.0)), 1),
            "f0_median": round(float(np.median(vv)), 1) if len(vv) > 5 else None,
            "f0_p10": round(float(np.percentile(vv, 10)), 1) if len(vv) > 5 else None,
            "f0_p90": round(float(np.percentile(vv, 90)), 1) if len(vv) > 5 else None}
    print("REF", json.dumps(info, ensure_ascii=False), flush=True)
    return info


refs = []
refs.append(build_ref("S03_v17", "ref_S03_female.wav"))
refs.append(build_ref("S06_v24", "ref_S06_female.wav"))
refs.append(build_ref("S01_v15", "ref_S01_male.wav"))
refs.append(build_ref("S05_v18", "ref_S05_male.wav"))
json.dump([r for r in refs if r], open(OUT + "refs.json", "w"), ensure_ascii=False, indent=1)
print("F0_DONE", flush=True)
