import json, subprocess
import numpy as np
from scipy.io import wavfile
from scipy.signal import butter, sosfilt
A="/var/aiadultvideo/output/aiadult/s06bv7/"
SR=16000
sos_bp=butter(4,[200,3400],btype="bandpass",fs=SR,output="sos")
def load(p):
    sr,x=wavfile.read(p); return x.astype(np.float64)
def analyze(tag,wav,clip_dur):
    x=load(wav); band=sosfilt(sos_bp,x)
    hop=160; n=len(band)//hop
    e=np.sqrt((band[:n*hop].reshape(n,hop)**2).mean(1)+1e-12)
    db=20*np.log10(e/32768.0)
    noise=float(np.percentile(db,10)); peak=float(np.percentile(db,99))
    thr=max(noise+8.0,peak-22.0)
    v=db>thr
    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
        if (j-i)*0.01>=0.03: segs.append((round(i*0.01,2),round(j*0.01,2)))
        i=j+1
    # cluster segments with gap <=0.45s
    clusters=[]
    for s in segs:
        if clusters and s[0]-clusters[-1][1]<=0.45: clusters[-1]=(clusters[-1][0],s[1])
        else: clusters.append(s)
    main=max(clusters,key=lambda c:c[1]-c[0]) if clusters else None
    es=np.convolve(db,np.ones(3)/3.0,mode="same")
    peaks=[]
    for k in range(2,len(es)-2):
        if es[k]>thr+2 and es[k]>=es[k-1] and es[k]>es[k+1] and es[k]>=es[k-2] and es[k]>=es[k+2]:
            if not peaks or (k-peaks[-1])*0.01>=0.055: peaks.append(k)
    nt=[round(p*0.01,2) for p in peaks]
    # nuclei inside main cluster only
    if main: nt=[t for t in nt if main[0]-0.05<=t<=main[1]+0.05]
    gaps=[round(nt[i+1]-nt[i],3) for i in range(len(nt)-1)]
    out={"tag":tag,"clip_dur":clip_dur,"segments":segs,"clusters":clusters,"main_cluster":main,
         "nuclei_main":len(nt),"nuclei_times":nt,"gaps":gaps,
         "main_len":round(main[1]-main[0],3) if main else None,
         "chars_per_sec_main":round(4.0/(main[1]-main[0]),2) if main else None,
         "tail_margin":round(clip_dur-main[1],3) if main else None,
         "noise_db":round(noise,1),"peak_db":round(peak,1)}
    return out
jobs=[("v7_107_s2026","S06b_v7_s2026_L107.wav",4.458),
      ("v7_124_s2026","S06b_v7_s2026_L124.wav",5.167),
      ("v7_124_s31","S06b_v7_s31_L124.wav",5.167)]
res=[]
for tag,w,d in jobs:
    r=analyze(tag,A+w,d); res.append(r); print(json.dumps(r,ensure_ascii=False),flush=True)
json.dump(res,open(A+"cluster.json","w"),ensure_ascii=False,indent=1)
print("CLUSTER_DONE",flush=True)
