#!/usr/bin/env python3
"""Re-runs the evidence check for the Tingyin post mandarin-tone-contours-measured.

Two kinds of row in dataset.json:

  page  a sentence quoted from a URL. The run fetches the page and looks for the
        sentence after normalising whitespace, quotes, dashes and HTML entities.
  lab   a number recomputed here. The run reads the app's own audio manifest from
        the repository, fetches every clip it names into a temporary cache, keeps
        a clip only when its sha256 equals the hash the manifest records, tracks a
        pitch contour per nucleus with the method in measure(), and compares the
        aggregates with the dataset.

Exit 0 when every row still holds, 1 otherwise. --recheck re-reads the cited pages
and skips the lab step, which downloads 637 files and takes several minutes.
--write rebuilds dataset.json and dataset.csv from a fresh measurement.

The manifest is in the Tingyin repository, so run this from a clone of it, or set
TINGYIN_REPO to one. Standard library plus numpy; ffmpeg and curl are subprocesses.
"""

import argparse
import concurrent.futures
import hashlib
import html
import json
import math
import os
import re
import subprocess
import sys
import tempfile
import threading
import time
import urllib.parse

import numpy as np

HERE = os.path.dirname(os.path.abspath(__file__))
DATASET = os.path.join(HERE, "dataset.json")
DATASET_CSV = os.path.join(HERE, "dataset.csv")

UA = "Mozilla/5.0"
# Wikimedia returns 429 to a bare browser string; its user-agent policy asks for a
# descriptive one, so clip downloads send this and the pages keep the browser string.
CLIP_UA = ("tingyin-evidence-check/1.0 "
           "(https://www.tingyin.app/blog/mandarin-tone-contours-measured)")
SR = 16000
WIN = 640  # 40 ms analysis window
HOP = 160  # 10 ms hop
F0_MIN, F0_MAX = 60.0, 400.0
LEVEL_ST = 2.5      # a contour whose 5th to 95th percentile span is under this is level
MOVE_ST = 2.0       # a rise or a fall has to move at least this far end to end
DIP_ST = 1.5        # each side of a dip has to clear its minimum by this much
MIN_VOICED = 8      # frames of pitch a nucleus needs before it can be graded

SHAPES = {1: "level", 2: "rise", 3: "dip", 4: "fall"}


def repo_root():
    root = os.environ.get("TINGYIN_REPO")
    if root:
        return root.strip()
    out = subprocess.run(["git", "-C", HERE, "rev-parse", "--show-toplevel"],
                         capture_output=True, text=True)
    return out.stdout.strip() if out.returncode == 0 else ""


# ---------------------------------------------------------------- page rows

def _strip_html(text):
    text = re.sub(r"<script.*?</script>", " ", text, flags=re.S | re.I)
    text = re.sub(r"<style.*?</style>", " ", text, flags=re.S | re.I)
    text = re.sub(r"<[^>]+>", " ", text)
    return html.unescape(text)


def normalise(text):
    text = html.unescape(text)
    for a, b in ((chr(0x2019), "'"), (chr(0x2018), "'"), (chr(0x201c), '"'),
                 (chr(0x201d), '"'), (chr(0x2013), "-"), (chr(0x2014), "-"),
                 (chr(0x00a0), " "), (chr(0x2212), "-")):
        text = text.replace(a, b)
    return re.sub(r"\s+", " ", text).strip().lower()


def fetch(url, timeout=90, agent=UA):
    out = subprocess.run(
        ["curl", "-sL", "--max-time", str(timeout), "-A", agent, url],
        capture_output=True)
    if out.returncode != 0:
        raise RuntimeError("curl exit %d" % out.returncode)
    return out.stdout.decode("utf-8", "replace")


def check_page(row):
    try:
        raw = fetch(row["url"])
    except Exception as exc:  # a page that refuses is not checked, never filled in
        return False, "fetch failed: %s" % exc
    body = raw
    if re.search(r"<\s*(html|body|div|p)\b", raw[:4000], re.I):
        body = _strip_html(raw)
    haystack = normalise(body)
    if normalise(row["quote"]) in haystack:
        return True, "quote found"
    return False, "quote not found in %d characters of text" % len(haystack)


# ---------------------------------------------------------------- lab rows

def load_wav(path):
    out = subprocess.run(
        ["ffmpeg", "-v", "error", "-i", path, "-ac", "1", "-ar", str(SR), "-f", "f32le", "-"],
        capture_output=True, check=True)
    x = np.frombuffer(out.stdout, dtype="<f4").astype(np.float64)
    if len(x) < WIN:
        x = np.pad(x, (0, WIN - len(x)))
    return x


def frame_signal(x):
    n = 1 + (len(x) - WIN) // HOP
    idx = np.arange(WIN)[None, :] + HOP * np.arange(n)[:, None]
    return x[idx]


def frame_db(frames):
    return 20 * np.log10(np.sqrt((frames ** 2).mean(axis=1)) + 1e-12)


def track_pitch(frames):
    """YIN: cumulative mean normalised difference, absolute threshold 0.30."""
    n, w = frames.shape
    x = frames - frames.mean(axis=1, keepdims=True)
    x = x * np.hanning(w)[None, :]
    nfft = 1 << int(math.ceil(math.log2(2 * w)))
    spec = np.fft.rfft(x, nfft, axis=1)
    acf = np.fft.irfft(spec * np.conj(spec), nfft, axis=1)[:, :w]
    sq = (x ** 2).sum(axis=1)
    cs = np.cumsum(x ** 2, axis=1)
    lag_min = int(SR / F0_MAX)
    lag_max = int(SR / F0_MIN)
    d = np.zeros((n, lag_max + 1))
    for t in range(1, lag_max + 1):
        e2 = cs[:, w - 1] - cs[:, w - 1 - t]
        d[:, t] = np.maximum(sq + e2 - 2 * acf[:, t], 0.0)
    cum = np.cumsum(d[:, 1:], axis=1)
    cmnd = np.ones_like(d)
    with np.errstate(divide="ignore", invalid="ignore"):
        cmnd[:, 1:] = d[:, 1:] * np.arange(1, lag_max + 1)[None, :] / cum
    cmnd = np.nan_to_num(cmnd, nan=1.0, posinf=1.0)
    cmnd[:, :lag_min] = 1.0
    f0 = np.full(n, np.nan)
    for i in range(n):
        row = cmnd[i]
        cand = np.where(row < 0.30)[0]
        if len(cand) == 0:
            continue
        t = cand[0]
        while t + 1 <= lag_max and row[t + 1] < row[t]:
            t += 1
        f0[i] = SR / t
    return f0


def find_nuclei(energy):
    """Voiced nuclei from the energy envelope: a region above the noise floor, then
    split at every interior valley at least 8 dB below the quieter of its two sides."""
    e = energy.copy()
    if len(e) >= 3:
        e[1:-1] = np.median(np.stack([energy[:-2], energy[1:-1], energy[2:]]), axis=0)
    floor = np.percentile(e, 10)
    peak = np.percentile(e, 95)
    above = e > max(floor + 8.0, peak - 30.0)
    idx = np.where(above)[0]
    if len(idx) == 0:
        return []
    groups, start, prev = [], idx[0], idx[0]
    for i in idx[1:]:
        if i - prev > 4:  # close gaps under 40 ms
            groups.append([start, prev])
            start = i
        prev = i
    groups.append([start, prev])

    out = []
    while groups:
        a, b = groups.pop()
        if b - a < 6:
            continue
        lo = a + max(3, (b - a) // 6)
        hi = b - max(3, (b - a) // 6)
        if hi <= lo:
            out.append((a, b))
            continue
        inner = e[lo:hi + 1]
        v = int(np.argmin(inner)) + lo
        depth_left = e[a:v + 1].max() - e[v]
        depth_right = e[v:b + 1].max() - e[v]
        if min(depth_left, depth_right) >= 8.0 and v - a >= 5 and b - v >= 5:
            groups.extend([[a, v - 1], [v + 1, b]])
        else:
            out.append((a, b))
    return sorted(g for g in out if g[1] - g[0] >= 6)


def active_span(energy):
    floor = np.percentile(energy, 10)
    peak = np.percentile(energy, 95)
    idx = np.where(energy > max(floor + 8.0, peak - 30.0))[0]
    return (int(idx[0]), int(idx[-1])) if len(idx) else None


def contour_of(f0, a, b):
    seg = f0[a:b + 1]
    seg = seg[~np.isnan(seg)]
    if len(seg) < MIN_VOICED:
        return None
    st = 12.0 * np.log2(seg / np.median(seg))
    if len(st) >= 5:
        st = np.convolve(st, np.ones(5) / 5.0, mode="valid")
    return st


def classify(core):
    q = max(1, int(len(core) * 0.25))
    start = float(np.median(core[:q]))
    end = float(np.median(core[-q:]))
    low = float(core.min())
    pos = (float(np.argmin(core)) + 0.5) / len(core)
    span = float(np.percentile(core, 95) - np.percentile(core, 5))
    if 0.15 <= pos <= 0.85 and (start - low) >= DIP_ST and (end - low) >= DIP_ST:
        return "dip"
    if end - start >= MOVE_ST:
        return "rise"
    if start - end >= MOVE_ST:
        return "fall"
    if span < LEVEL_ST:
        return "level"
    return "other"


def shape_of(st):
    if st is None or len(st) < 5:
        return "ungraded"
    trim = int(len(st) * 0.15)
    core = st[trim:len(st) - trim] if len(st) - 2 * trim >= 5 else st
    return classify(core)


def clip_urls(root):
    manifest = json.load(open(os.path.join(root, "fixtures", "audio-manifest.json")))
    ll = json.load(open(os.path.join(root, "fixtures", "lingua-libre", "manifest.json")))
    ll_by_id = {e["id"]: e for e in ll["entries"]}
    urls = {}
    for entry in manifest:
        if entry["source"] == "lingua-libre":
            urls[entry["id"]] = ll_by_id[entry["id"]]["recordings"][0]["fileUrl"]
        else:
            sub = "64k/syllabs" if entry["source"] == "audio-cmn-syllables" else "96k/hsk"
            urls[entry["id"]] = (
                "https://raw.githubusercontent.com/hugolpz/audio-cmn/master/%s/%s"
                % (sub, urllib.parse.quote(entry["srcFile"], safe=""))
            )
    return manifest, urls


def download(url, dest, sha, tries=5):
    """Fetch one clip and keep it only if its bytes are the ones the manifest names."""
    agent = CLIP_UA if "upload.wikimedia.org" in url else UA
    for attempt in range(tries):
        out = subprocess.run(
            ["curl", "-sL", "--max-time", "120", "-A", agent, "-w", "%{http_code}", "-o", dest, url],
            capture_output=True)
        code = out.stdout.decode().strip()[-3:]
        if out.returncode == 0 and code == "200" and os.path.exists(dest):
            if hashlib.sha256(open(dest, "rb").read()).hexdigest() == sha:
                return True
        if os.path.exists(dest):
            os.remove(dest)
        time.sleep(5 if code in ("429", "503", "502", "500") else 2)
    return False


def fetch_clips(root, cache):
    manifest, urls = clip_urls(root)
    os.makedirs(cache, exist_ok=True)
    todo = []
    reused = 0
    for entry in manifest:
        dest = os.path.join(cache, entry["file"])
        if os.path.exists(dest) and hashlib.sha256(open(dest, "rb").read()).hexdigest() == entry["sha256"]:
            reused += 1
        else:
            todo.append(entry)
    fetched, missing = 0, []
    lock = threading.Lock()

    def work(entry):
        nonlocal fetched
        ok = download(urls[entry["id"]], os.path.join(cache, entry["file"]), entry["sha256"])
        with lock:
            if ok:
                fetched += 1
            else:
                missing.append(entry["id"])

    with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool:
        list(pool.map(work, todo))
    return manifest, {"fetched": fetched, "reused": reused, "missing": missing}


def measure(root, cache):
    manifest, _ = clip_urls(root)
    graded = {t: 0 for t in SHAPES}
    matched = {t: 0 for t in SHAPES}
    single_graded = {t: 0 for t in SHAPES}
    single_matched = {t: 0 for t in SHAPES}
    sha_ok = agree = 0

    for entry in manifest:
        path = os.path.join(cache, entry["file"])
        if not os.path.exists(path):
            continue
        if hashlib.sha256(open(path, "rb").read()).hexdigest() != entry["sha256"]:
            continue
        sha_ok += 1
        try:
            frames = frame_signal(load_wav(path))
        except subprocess.CalledProcessError:
            continue
        energy = frame_db(frames)
        f0 = track_pitch(frames)
        nuclei = find_nuclei(energy)

        # Multi-syllable clips: a nucleus maps to a tone only when the segmenter
        # found the number of nuclei the word claims, so the rest are skipped.
        if len(nuclei) == entry["syllableCount"]:
            agree += 1
            for (a, b), tone in zip(nuclei, entry["tones"]):
                if tone not in SHAPES:
                    continue
                shape = shape_of(contour_of(f0, a, b))
                if shape == "ungraded":
                    continue
                graded[tone] += 1
                if shape == SHAPES[tone]:
                    matched[tone] += 1

        # A clip of one syllable needs no segmentation at all: its whole voiced span
        # is the nucleus, so it is graded even where the finder split or merged it.
        if entry["syllableCount"] == 1:
            span = active_span(energy)
            tone = entry["tones"][0]
            if span and tone in SHAPES:
                shape = shape_of(contour_of(f0, span[0], span[1]))
                if shape != "ungraded":
                    single_graded[tone] += 1
                    if shape == SHAPES[tone]:
                        single_matched[tone] += 1

    return {
        "clips": len(manifest),
        "sha_ok": sha_ok,
        "agree": agree,
        "graded": graded,
        "matched": matched,
        "single_graded": single_graded,
        "single_matched": single_matched,
    }


def share(matched, graded):
    if not graded:
        return "0 of 0"
    return "%d of %d = %.4f" % (matched, graded, matched / graded)


def lab_value(rid, m):
    """The row's value recomputed from the measurement of the shipped clips."""
    if rid == "SHIP-01":
        return "%d of %d" % (m["clips"], m["clips"])
    if rid == "SHIP-02":
        return "%d of %d" % (m["sha_ok"], m["clips"])
    if rid == "SHIP-03":
        return "%d of %d" % (m["agree"], m["clips"])
    all_tone = {"SHIP-04": 1, "SHIP-05": 2, "SHIP-06": 3, "SHIP-07": 4,
                "SHIP-12": 1, "SHIP-13": 2, "SHIP-14": 3, "SHIP-15": 4}
    tone = all_tone[rid]
    if rid.startswith("SHIP-0"):
        return share(m["matched"][tone], m["graded"][tone])
    return share(m["single_matched"][tone], m["single_graded"][tone])


def _csv(value):
    text = str(value)
    if any(c in text for c in ',"\n'):
        return '"%s"' % text.replace('"', '""')
    return text


def write_csv(data):
    fields = ("id", "group", "option", "property", "value", "n", "unit")
    with open(DATASET_CSV, "w") as fh:
        fh.write(",".join(fields) + ",source\n")
        for row in data["results"]:
            cells = [row.get(f, "") for f in fields]
            cells.append(row.get("url") or row.get("source_file", ""))
            fh.write(",".join(_csv(c) for c in cells) + "\n")


def write_outputs(data, m):
    for row in data["results"]:
        if row["kind"] != "lab":
            continue
        value = lab_value(row["id"], m)
        row["value"] = value
        head, _, tail = value.partition(" of ")
        if tail:
            row["n"] = int(tail.split(" = ")[0].split(" ")[0])
    with open(DATASET, "w") as fh:
        json.dump(data, fh, indent=1, ensure_ascii=False)
        fh.write("\n")
    write_csv(data)
    print("wrote dataset.json and dataset.csv")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--recheck", action="store_true",
                    help="re-read the cited pages and skip the lab measurement")
    ap.add_argument("--cache", default=os.path.join(tempfile.gettempdir(),
                                                    "tingyin-tone-contours-clips"),
                    help="where downloaded clips are kept between runs")
    ap.add_argument("--fetch-only", action="store_true", help="download the clips and stop")
    ap.add_argument("--write", action="store_true",
                    help="rebuild dataset.json and dataset.csv from a fresh measurement")
    ap.add_argument("--csv", action="store_true",
                    help="rewrite dataset.csv from dataset.json without measuring")
    args = ap.parse_args()

    if args.csv:
        write_csv(json.load(open(DATASET)))
        print("wrote dataset.csv")
        return 0

    root = repo_root()
    if not os.path.exists(os.path.join(root, "fixtures", "audio-manifest.json")):
        print("no fixtures/audio-manifest.json under %r. Run from a clone of the Tingyin "
              "repository or set TINGYIN_REPO." % (root or "the current directory"))
        return 1

    if args.fetch_only:
        _, stats = fetch_clips(root, args.cache)
        print("fetch: %d fetched, %d already cached, %d failed"
              % (stats["fetched"], stats["reused"], len(stats["missing"])))
        return 0 if not stats["missing"] else 1

    data = json.load(open(DATASET))
    rows = data["results"]

    if args.write:
        _, stats = fetch_clips(root, args.cache)
        if stats["missing"]:
            print("fetch: %d clips could not be downloaded: %s"
                  % (len(stats["missing"]), ", ".join(stats["missing"][:10])))
            return 1
        write_outputs(data, measure(root, args.cache))
        return 0

    failures = 0
    for row in rows:
        if row["kind"] != "page":
            continue
        ok, why = check_page(row)
        print("%-8s %-6s %s  %s" % (row["id"], "page", "ok" if ok else "FAIL", why))
        if not ok:
            print("         url: %s" % row["url"])
            failures += 1

    lab_rows = [r for r in rows if r["kind"] == "lab"]
    if args.recheck:
        print("lab      skipped  %d rows (downloads 637 clips; run without --recheck)"
              % len(lab_rows))
    else:
        _, stats = fetch_clips(root, args.cache)
        print("fetch    %d fetched, %d cached, %d failed"
              % (stats["fetched"], stats["reused"], len(stats["missing"])))
        if stats["missing"]:
            print("         missing: %s" % ", ".join(stats["missing"][:10]))
            failures += 1
        m = measure(root, args.cache)
        print("lab      sha256 verified %d/%d, nucleus count matched the claimed count in %d clips"
              % (m["sha_ok"], m["clips"], m["agree"]))
        for row in lab_rows:
            value = lab_value(row["id"], m)
            ok = value == row["value"]
            print("%-8s %-6s %s  stored %s, measured %s"
                  % (row["id"], "lab", "ok" if ok else "FAIL", row["value"], value))
            if not ok:
                failures += 1

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


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