# Usage: python3 check.py <source> <cut> <start> <end>   Times in seconds (204) or m:ss (3:24). Prints duration error, codec, and whether every cut packet is a contiguous copy of source packets.
import subprocess, sys, json, os, re
if len(sys.argv) < 5: sys.exit("usage: python3 check.py <source> <cut> <start> <end>   (times as 204 or 3:24)")
def secs(t):
    t = t.strip()
    try: return sum(float(x) * 60 ** i for i, x in enumerate(reversed(t.split(":"))))
    except ValueError: sys.exit(f"not a time: {t!r} (use seconds like 204 or m:ss like 3:24)")
src, cut, a, b = sys.argv[1], sys.argv[2], secs(sys.argv[3]), secs(sys.argv[4])
for f in (src, cut):
    if not os.path.isfile(f) or os.path.getsize(f) == 0: sys.exit(f"missing or empty file: {f}")
def probe(f):
    j = json.loads(subprocess.run(["ffprobe","-v","error","-show_entries","format=duration,bit_rate:stream=codec_name,sample_rate,channels","-of","json",f],capture_output=True,text=True).stdout or "{}")
    if "format" not in j or not j.get("streams"): sys.exit(f"not an audio file: {f}")
    return j["format"], j["streams"][0]
def md5s(f):
    o = subprocess.run(["ffmpeg","-v","error","-i",f,"-map","0:a","-c","copy","-f","framemd5","-"],capture_output=True,text=True).stdout
    return [l.split(",")[5].strip() for l in o.splitlines() if l and not l.startswith("#")]
def lufs(f):
    e = subprocess.run(["ffmpeg","-hide_banner","-nostats","-i",f,"-af","ebur128=peak=true","-f","null","-"],capture_output=True,text=True).stderr
    s = e[e.rfind("Summary:"):]
    g = lambda k: re.search(k+r":\s+(-?[\d.]+)", s).group(1)
    return g("I"), g("LRA"), g("Peak")
fs, ss = probe(src); fc, sc = probe(cut)
want = b - a; got = float(fc["duration"])
r = {"cut": cut, "requested_s": round(want,3), "measured_s": round(got,6), "error_ms": round((got-want)*1000,1),
     "codec": sc["codec_name"], "sample_rate": sc["sample_rate"], "channels": sc["channels"], "kbps": round(int(fc["bit_rate"])/1000)}
if ss["codec_name"] == "mp3":
    S, C = md5s(src), md5s(cut)
    k = next((i for i in range(len(S)-len(C)+1) if S[i:i+len(C)] == C), None)
    r["packets"] = len(C); r["copied_from_source_packet"] = k; r["frame_copy"] = k is not None
    r["start_frame_s"] = None if k is None else round(k*1152/int(ss["sample_rate"]),3)
else:
    r["frame_copy"] = False; r["note"] = "source codec " + ss["codec_name"] + ", re-encoded"
r["lufs_I"], r["LRA"], r["true_peak_dbfs"] = lufs(cut)
print(json.dumps(r))
