"""Score a Caption Fieldnotes whisper.cpp or Vosk JSON result against its reference.

Example: python3 score.py studio-check-reference.json studio-check-whisper-tiny.en.json
This example normalizes English words. It does not score speaker labels or confidence.
"""
import argparse
import json
import re
from pathlib import Path
from statistics import mean


def tokens(text):
    return re.findall(r"[a-z0-9]+(?:'[a-z0-9]+)*", text.lower().replace("’", "'"))


def edit_distance(expected, observed):
    previous = list(range(len(observed) + 1))
    for row, word in enumerate(expected, 1):
        current = [row]
        for index, guess in enumerate(observed, 1):
            current.append(min(previous[index] + 1, current[-1] + 1,
                               previous[index - 1] + (word != guess)))
        previous = current
    return previous[-1]


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("reference", type=Path)
    parser.add_argument("recognition", type=Path)
    args = parser.parse_args()
    turns = json.loads(args.reference.read_text(encoding="utf-8"))["turns"]
    recognition = json.loads(args.recognition.read_text(encoding="utf-8"))
    if "transcription" in recognition:
        predictions = recognition["transcription"]
        engine = "whisper.cpp"
    elif "results" in recognition:
        predictions = recognition["results"]
        engine = "Vosk"
    else:
        raise ValueError("Expected whisper.cpp transcription or Vosk results")
    expected = tokens(" ".join(t["text"] for t in turns))
    observed = tokens(" ".join(t["text"] for t in predictions))
    if not expected:
        raise ValueError("The reference must contain words")
    edits = edit_distance(expected, observed)
    print(f"Word error rate: {edits} edits / {len(expected)} reference words = {100 * edits / len(expected):.2f}%")
    if engine == "Vosk":
        print("Vosk endpoint blocks are decoder boundaries. Only the words are compared here.")
    elif len(predictions) == len(turns) and turns:
        for field, key in [("start", "from"), ("end", "to")]:
            errors = [abs(round(ref[field] * 1000) - hyp["offsets"][key])
                      for ref, hyp in zip(turns, predictions)]
            print(f"Mean absolute cue {field} difference (paired by order): {mean(errors):.2f} ms")
    else:
        print("Cue counts differ. Inspect segment correspondence before pairing boundaries.")


if __name__ == "__main__":
    main()
