#!/usr/bin/env python3
"""Re-runs the check behind the four-mandarin-tones dataset.

lab: downloads the 80 level-1 recordings from the URLs Tingyin serves publicly,
requires each to match the sha256 in fixtures/audio-manifest.json, decodes it
with ffmpeg and measures pitch with a YIN tracker. The corpus counts the post
quotes are recounted from the same manifest.

primary-docs: re-fetches every page the post cites and requires the supporting
sentence to still be on it.

endpoint: re-reads the public plans endpoint and requires the USD prices the
post publishes.

    python3 check.py            everything, exit 0 when every row holds
    python3 check.py --recheck  same, but a lab step over one minute is skipped

Needs numpy and ffmpeg on PATH.
"""

import argparse
import hashlib
import html
import io
import json
import os
import re
import subprocess
import sys
import tempfile
import time
import unicodedata
import urllib.request
import wave

import numpy as np

HERE = os.path.dirname(os.path.abspath(__file__))
DATASET = os.path.join(HERE, "dataset.json")
AUDIO = "https://www.tingyin.app/audio/%s"
PLANS = "https://api.tingyin.app/subscriptions/plans"
UA = "Mozilla/5.0 (compatible; article-quality-recheck; +https://www.tingyin.app)"
SR = 22050
FRAME_S = 0.040
HOP_S = 0.005
F0_MIN = 90.0
F0_MAX = 400.0
QMAX = 0.30


def repo_root():
    path = HERE
    for _ in range(8):
        if os.path.exists(os.path.join(path, "fixtures", "audio-manifest.json")):
            return path
        path = os.path.dirname(path)
    raise SystemExit("fixtures/audio-manifest.json not found above %s" % HERE)


# ---------------------------------------------------------------- text checks

def normalise(text):
    """Whitespace, HTML entities, curly quotes and dashes folded to one form."""
    text = html.unescape(text)
    text = unicodedata.normalize("NFKC", text)
    for a, b in (("‘", "'"), ("’", "'"), ("“", '"'),
                 ("”", '"'), ("–", "-"), ("—", "-"),
                 ("−", "-"), (" ", " ")):
        text = text.replace(a, b)
    return re.sub(r"\s+", " ", text).strip()


def strip_html(markup):
    markup = re.sub(r"<(script|style)\b.*?</\1>", " ", markup, flags=re.S | re.I)
    markup = re.sub(r"<[^>]+>", " ", markup)
    return normalise(markup)


def fetch(url, binary=False):
    req = urllib.request.Request(url, headers={"User-Agent": UA})
    with urllib.request.urlopen(req, timeout=45) as resp:
        body = resp.read()
    if binary:
        return body
    for enc in ("utf-8", "latin-1"):
        try:
            return body.decode(enc)
        except UnicodeDecodeError:
            continue
    return body.decode("utf-8", "replace")


def quote_present(row):
    page = fetch(row["url"])
    text = page if row["url"].endswith(".md") else strip_html(page)
    return normalise(row["quote"]) in text


def prices_present(row):
    plans = json.loads(fetch(row["url"]))
    premium = next(p for p in plans["plans"] if p["tier"] == "premium")
    pricing = premium["pricing"]
    web = {o["id"]: o["web"] for o in pricing["options"]}
    return (pricing["currency"] == "usd"
            and web.get("weekly") == row["weekly"]
            and web.get("monthly") == row["monthly"]
            and web.get("lifetime") == row["lifetime"])


# ------------------------------------------------------- measurement pipeline

def decode(path):
    proc = subprocess.run(
        ["ffmpeg", "-v", "error", "-i", path, "-ac", "1", "-ar", str(SR), "-f", "wav", "-"],
        capture_output=True, check=True)
    with wave.open(io.BytesIO(proc.stdout)) as w:
        assert w.getsampwidth() == 2, "expected 16-bit output from ffmpeg"
        data = np.frombuffer(w.readframes(w.getnframes()), dtype="<i2")
    return data.astype(np.float64) / 32768.0


def yin_frames(x, fmin=F0_MIN, fmax=F0_MAX, frame=FRAME_S, hop=HOP_S,
               thresh=0.20, gate_frac=0.12):
    """Per-frame f0 with a cumulative-mean-normalised difference function."""
    n = int(round(frame * SR))
    h = int(round(hop * SR))
    tmin = max(2, int(np.floor(SR / fmax)))
    tmax = int(np.ceil(SR / fmin))
    count = max(0, 1 + (len(x) - n) // h)
    if count == 0:
        return []
    rms = np.array([float(np.sqrt(np.mean(x[i*h:i*h+n]**2))) for i in range(count)])
    gate = max(0.02, gate_frac * float(rms.max()))
    taus = np.arange(tmax + 2)
    out = []
    for i in range(count):
        if rms[i] < gate:
            out.append((None, 1.0))
            continue
        seg = x[i*h:i*h+n]
        seg = seg - seg.mean()
        spec = np.fft.rfft(seg, 2 * n)
        acf = np.fft.irfft(spec * np.conj(spec), 2 * n)[:tmax + 2]
        cs = np.concatenate(([0.0], np.cumsum(seg * seg)))
        e1 = cs[np.clip(n - taus, 0, n)]
        e2 = cs[n] - cs[np.clip(taus, 0, n)]
        d = np.maximum(e1 + e2 - 2.0 * acf, 0.0)
        d[0] = 0.0
        run = np.cumsum(d)
        with np.errstate(divide="ignore", invalid="ignore"):
            cmnd = np.where(run > 0, d * taus / run, 1.0)
        cmnd[0] = 1.0
        cand = None
        for tau in range(tmin, tmax + 1):
            if cmnd[tau] < thresh:
                while tau + 1 <= tmax and cmnd[tau + 1] < cmnd[tau]:
                    tau += 1
                cand = tau
                break
        if cand is None:
            k = tmin + int(np.argmin(cmnd[tmin:tmax + 1]))
            if cmnd[k] > 0.50:
                out.append((None, float(cmnd[k])))
                continue
            cand = k
        q = float(cmnd[cand])
        a, b, c = cmnd[cand-1], cmnd[cand], cmnd[cand+1]
        den = a - 2 * b + c
        shift = 0.5 * (a - c) / den if den != 0 else 0.0
        f = float(SR / (cand + max(-1.0, min(1.0, shift))))
        out.append((f if q <= QMAX else None, q))
    return out


def contour(x):
    """Octave-snapped, median-smoothed f0 track of the voiced frames."""
    frames = yin_frames(x)
    voiced = [(i, f) for i, (f, _) in enumerate(frames) if f]
    if len(voiced) < 15:
        return None
    ref = float(np.median([f for _, f in voiced]))
    snapped = {}
    for i, f in voiced:
        while np.log2(f / ref) > 0.6:
            f /= 2.0
        while np.log2(f / ref) < -0.6:
            f *= 2.0
        snapped[i] = f
    order = sorted(snapped)
    for _ in range(2):
        smooth = dict(snapped)
        for j, i in enumerate(order):
            near = [snapped[order[k]] for k in range(max(0, j-2), min(len(order), j+3))]
            smooth[i] = float(np.median(near))
        snapped = smooth
    return np.array([snapped[i] for i in order])


def tone_shape(samples):
    """start (10-25 %), minimum (5-frame median, 20-95 %), end (80-95 %)."""
    fs = contour(samples)
    if fs is None:
        return None
    n = len(fs)

    def win(a, b):
        lo = int(round(a * (n - 1)))
        hi = max(lo + 1, int(round(b * (n - 1))))
        return float(np.median(fs[lo:hi + 1]))

    lo_i = int(round(0.20 * (n - 1)))
    hi_i = int(round(0.95 * (n - 1)))
    seg = fs[lo_i:hi_i + 1]
    w = 5 if len(seg) >= 5 else 1
    smooth = np.array([np.median(seg[j:j + w]) for j in range(len(seg) - w + 1)])
    k = int(np.argmin(smooth))
    return {
        "start": win(0.10, 0.25),
        "min": float(smooth[k]),
        "end": win(0.80, 0.95),
        "dipPos": (lo_i + k + w / 2.0) / (n - 1),
        "n": n,
    }


def semitones(f, ref):
    return 12.0 * np.log2(f / ref)


class LabTooSlow(Exception):
    pass


def measure_lab(deadline=None):
    """Every lab metric the dataset records, recomputed from inputs downloaded now."""
    manifest = json.load(open(os.path.join(repo_root(), "fixtures", "audio-manifest.json")))
    level1 = [e for e in manifest if e["level"] == 1]
    tone_of = {e["id"]: e["tones"][0] for e in level1}

    work = tempfile.mkdtemp(prefix="four-tones-")
    hashes_ok = 0
    shapes = {}
    durations = {}
    for e in level1:
        if deadline is not None and time.monotonic() > deadline:
            raise LabTooSlow("lab measurement hit the one-minute recheck budget")
        path = os.path.join(work, e["file"])
        body = fetch(AUDIO % e["file"], binary=True)
        open(path, "wb").write(body)
        hashes_ok += hashlib.sha256(body).hexdigest() == e["sha256"]
        samples = decode(path)
        durations[e["id"]] = len(samples) / float(SR)
        shapes[e["id"]] = tone_shape(samples)

    speaker = float(np.median([v for s in shapes.values() if s
                               for v in (s["start"], s["end"])]))

    m = {"hashes-ok": hashes_ok, "speaker-hz": speaker}
    for t in (1, 2, 3, 4):
        rows = [shapes[c] for c in shapes if tone_of[c] == t and shapes[c]]
        if not rows:
            continue
        start = float(np.median([r["start"] for r in rows]))
        dip = float(np.median([r["min"] for r in rows]))
        end = float(np.median([r["end"] for r in rows]))
        m["tone%d-n" % t] = len(rows)
        m["tone%d-start" % t] = float(semitones(start, speaker))
        m["tone%d-min" % t] = float(semitones(dip, speaker))
        m["tone%d-end" % t] = float(semitones(end, speaker))
        m["tone%d-span" % t] = float(semitones(end, speaker) - semitones(start, speaker))
        m["tone%d-drop" % t] = float(semitones(dip, speaker) - semitones(start, speaker))
        m["tone%d-return" % t] = float(semitones(end, speaker) - semitones(dip, speaker))
        m["tone%d-dipPos" % t] = float(np.median([r["dipPos"] for r in rows]))
        m["tone%d-len" % t] = float(np.mean([durations[c] for c in shapes if tone_of[c] == t]))
        rate = [abs(semitones(r["min"], speaker) - semitones(r["start"], speaker))
                / durations[c] for c, r in ((c, shapes[c]) for c in shapes
                                            if tone_of[c] == t and shapes[c])]
        m["tone%d-rate" % t] = float(np.median(rate))
        if t == 3:
            m["tone3-share-return"] = float(np.mean(
                [semitones(r["end"], speaker) - semitones(r["min"], speaker) >= 1.0 for r in rows]))
        if t == 2:
            m["tone2-share-rise"] = float(np.mean(
                [semitones(r["end"], speaker) - semitones(r["start"], speaker) >= 2.0 for r in rows]))
        if t == 1:
            m["tone1-share-level"] = float(np.mean(
                [abs(semitones(r["end"], speaker) - semitones(r["start"], speaker)) <= 1.0
                 for r in rows]))

    m["start-gap-t2-t3"] = m["tone2-start"] - m["tone3-start"]
    m["floor-gap-t4-t3"] = m["tone4-min"] - m["tone3-min"]

    single = [e for e in manifest if e["level"] in (1, 2)]
    m["corpus-total"] = len(manifest)
    m["corpus-single"] = len(single)
    for lvl in (1, 2, 3, 4):
        m["corpus-level%d" % lvl] = sum(1 for e in manifest if e["level"] == lvl)
    for t in (1, 2, 3, 4):
        durs = [e["duration_s"] for e in single if e["tones"][0] == t]
        m["dur-tone%d" % t] = float(np.mean(durs))
    peaks = {t: float(np.mean([e["maxVolumeDbfs"] for e in single if e["tones"][0] == t]))
             for t in (1, 2, 3, 4)}
    m["peak-spread"] = float(max(peaks.values()) - min(peaks.values()))
    levels = {t: float(np.mean([e["meanVolumeDbfs"] for e in single if e["tones"][0] == t]))
              for t in (1, 2, 3, 4)}
    m["level-gap-t4-t1"] = float(levels[1] - levels[4])
    m["neutral-total"] = sum(1 for e in manifest if 5 in e["tones"])
    m["neutral-single"] = sum(1 for e in manifest if 5 in e["tones"] and e["level"] in (1, 2))
    m["sandhi-t3t3"] = sum(1 for e in manifest if tuple(e["tones"]) == (3, 3))
    for name in ("Yue Tan", "Chen Wang"):
        m["speaker-%s" % name.lower().replace(" ", "-")] = sum(
            1 for e in manifest if e["speaker"] == name)
    libres = [e for e in manifest if e["source"] == "lingua-libre"]
    m["speaker-lingua-libre"] = len(libres)
    m["speaker-lingua-libre-named"] = len({e["speaker"] for e in libres})
    m["duration-files-match"] = sum(
        1 for e in level1 if abs(durations[e["id"]] - e["duration_s"]) <= 0.05)
    return m


# --------------------------------------------------------------------- main

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--recheck", action="store_true",
                    help="re-read pages and skip a lab step over one minute")
    ap.add_argument("--emit", action="store_true",
                    help="print measured values as JSON and exit")
    args = ap.parse_args()

    started = time.time()
    try:
        metrics = measure_lab(time.monotonic() + 60 if args.recheck else None)
    except LabTooSlow as exc:
        print("lab: %s" % exc)
        metrics = None
    took = time.time() - started

    if args.emit:
        json.dump({"metrics": metrics, "lab_seconds": round(took, 1)},
                  sys.stdout, indent=1, sort_keys=True)
        sys.stdout.write("\n")
        return 0

    dataset = json.load(open(DATASET))
    failures = 0
    print("lab measurement: %.1fs" % took)
    for row in dataset["results"]:
        method = row["method"]
        if method == "lab":
            key = row["metric"]
            if metrics is None:
                print("SKIP  %-28s (recheck: lab skipped)" % key)
                continue
            got = metrics.get(key)
            if got is None:
                print("FAIL  %-28s not measured" % key)
                failures += 1
                continue
            want = row["measured"]
            tol = row.get("tolerance", 0.05)
            ok = abs(got - want) <= tol
            failures += not ok
            print("%s  %-28s measured %-10s recorded %s"
                  % ("PASS" if ok else "FAIL", key, round(got, 3), want))
            continue
        try:
            if method == "primary-docs":
                ok = quote_present(row)
            elif method == "endpoint":
                ok = prices_present(row)
            else:
                raise SystemExit("unknown method %r" % method)
            note = row["url"]
        except Exception as exc:                      # a page that refuses us
            ok = False
            note = "%s (%s: %s)" % (row["url"], type(exc).__name__, exc)
        failures += not ok
        print("%s  %-28s %s" % ("PASS" if ok else "FAIL", row["id"], note))

    print("\n%d failure(s)" % failures)
    return 0 if failures == 0 else 1


if __name__ == "__main__":
    sys.exit(main())
