#!/usr/bin/env python3
"""One-clip CPU check, not a general ASR benchmark. See README.txt."""
import argparse
import gc
import hashlib
import importlib.metadata
import json
import os
import platform
import re
import statistics
import subprocess
import time
from datetime import datetime, timezone
from pathlib import Path


def sha256(path):
    with open(path, "rb") as handle:
        return hashlib.file_digest(handle, "sha256").hexdigest()


def words(text):
    # Case/punctuation ignored; internal apostrophes retained. No brand correction.
    return re.findall(r"[a-z0-9]+(?:'[a-z0-9]+)*", text.lower().replace("’", "'"))


def score(reference, hypothesis):
    ref, hyp = words(reference), words(hypothesis)
    if not ref:
        raise ValueError("Reference must contain at least one scored word")
    distances = [[0] * (len(hyp) + 1) for _ in range(len(ref) + 1)]
    for i in range(len(ref) + 1):
        distances[i][0] = i
    for j in range(len(hyp) + 1):
        distances[0][j] = j
    for i in range(1, len(ref) + 1):
        for j in range(1, len(hyp) + 1):
            distances[i][j] = min(
                distances[i - 1][j - 1] + (ref[i - 1] != hyp[j - 1]),
                distances[i - 1][j] + 1, distances[i][j - 1] + 1,
            )
    i, j = len(ref), len(hyp)
    errors = []
    while i or j:
        if i and j and ref[i - 1] == hyp[j - 1] and distances[i][j] == distances[i - 1][j - 1]:
            i, j = i - 1, j - 1
        elif i and j and distances[i][j] == distances[i - 1][j - 1] + 1:
            errors.append({"type": "substitution", "reference": ref[i - 1], "hypothesis": hyp[j - 1]})
            i, j = i - 1, j - 1
        elif i and distances[i][j] == distances[i - 1][j] + 1:
            errors.append({"type": "deletion", "reference": ref[i - 1], "hypothesis": ""})
            i -= 1
        else:
            errors.append({"type": "insertion", "reference": "", "hypothesis": hyp[j - 1]})
            j -= 1
    counts = {kind + "s": sum(e["type"] == kind for e in errors) for kind in ("substitution", "deletion", "insertion")}
    return {**counts, "reference_words": len(ref), "word_errors": len(errors),
            "wer": len(errors) / len(ref), "errors": list(reversed(errors))}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--audio", type=Path, required=True)
    parser.add_argument("--reference", type=Path, required=True)
    parser.add_argument("--output", type=Path, default=Path("results.json"))
    parser.add_argument("--cache", type=Path, default=Path("model-cache"))
    parser.add_argument("--cpu-label", default="unspecified")
    parser.add_argument("--memory-gib", type=float, default=None)
    parser.add_argument("--threads", type=int, default=4)
    parser.add_argument("--warm-runs", type=int, default=3)
    args = parser.parse_args()
    if args.warm_runs < 1 or args.threads < 1:
        parser.error("--warm-runs and --threads must be positive")
    import imageio_ffmpeg
    import numpy as np
    import torch
    import whisper
    import truststore

    # Use OS certificate authorities; never disable TLS verification.
    truststore.inject_into_ssl()

    torch.set_num_threads(args.threads)
    torch.set_num_interop_threads(1)
    torch.manual_seed(0)
    ffmpeg = imageio_ffmpeg.get_ffmpeg_exe()
    ffmpeg_version = subprocess.check_output([ffmpeg, "-version"], text=True).splitlines()[0]
    decode_start = time.perf_counter()
    raw = subprocess.check_output([ffmpeg, "-nostdin", "-threads", "1", "-i", str(args.audio),
                                   "-f", "f32le", "-ac", "1", "-ar", "16000", "-loglevel", "error", "-"])
    audio = np.frombuffer(raw, np.float32).copy()
    decode_seconds = time.perf_counter() - decode_start
    reference = args.reference.read_text(encoding="utf-8").strip()
    options = dict(language="en", task="transcribe", fp16=False, temperature=0.0,
                   beam_size=None, best_of=None, condition_on_previous_text=False,
                   initial_prompt=None, without_timestamps=True, word_timestamps=False,
                   compression_ratio_threshold=None, logprob_threshold=None,
                   no_speech_threshold=None, suppress_tokens="-1", verbose=None)
    packages = ("openai-whisper", "torch", "numpy", "imageio-ffmpeg", "numba", "llvmlite", "tiktoken", "more-itertools", "tqdm", "truststore")
    result = {
        "run_date_utc": datetime.now(timezone.utc).isoformat(),
        "scope": "One short English VocalJet demo clip; not a model ranking or general accuracy estimate.",
        "reference_provenance": "Existing public VocalJet demo transcript; no independent annotation panel.",
        "hardware": {"cpu": args.cpu_label, "architecture": platform.machine(), "logical_cpus": os.cpu_count(),
                     "memory_gib": args.memory_gib, "os": platform.system(), "os_release": platform.release()},
        "software": {"python": platform.python_version(), "packages": {p: importlib.metadata.version(p) for p in packages}, "ffmpeg": ffmpeg_version},
        "configuration": {"device": "cpu", "precision": "float32", "torch_threads": args.threads,
                          "torch_interop_threads": 1, "seed": 0, "audio_sample_rate": 16000, "audio_channels": 1,
                          "model_order": ["tiny.en", "base.en"], "first_runs": 1, "warm_runs": args.warm_runs,
                          "transcribe_options": options},
        "audio": {"filename": args.audio.name, "sha256": sha256(args.audio), "bytes": args.audio.stat().st_size,
                  "decoded_samples": len(audio), "duration_seconds": len(audio) / 16000, "decode_seconds": decode_seconds},
        "reference": {"filename": args.reference.name, "sha256": sha256(args.reference), "text": reference,
                      "normalization": "ASCII English words/numbers, lowercase, punctuation ignored, internal apostrophes retained; no brand normalization.",
                      "word_count": len(words(reference))},
        "timing_notes": "Download/check excluded from model load. Load includes cached checkpoint SHA check and CPU model initialization. First inference and three warm runs are separate. Audio decode excluded from inference. No concurrent benchmark models; machine was not otherwise isolated.",
        "models": [],
    }
    args.cache.mkdir(parents=True, exist_ok=True)
    for name in ("tiny.en", "base.en"):
        # These private symbols are pinned by the published openai-whisper version.
        url = whisper._MODELS[name]
        cached_before = (args.cache / (name + ".pt")).is_file()
        start = time.perf_counter()
        checkpoint = whisper._download(url, str(args.cache), False)
        download_seconds = time.perf_counter() - start
        start = time.perf_counter()
        model = whisper.load_model(name, device="cpu", download_root=str(args.cache))
        load_seconds = time.perf_counter() - start
        row = {"name": name, "checkpoint_url": url, "checkpoint_sha256": sha256(checkpoint),
               "cached_before_run": cached_before, "download_or_check_seconds": download_seconds,
               "model_load_seconds": load_seconds, "runs": []}
        for index in range(1 + args.warm_runs):
            start = time.perf_counter()
            with torch.inference_mode():
                output = model.transcribe(audio, **options)
            elapsed = time.perf_counter() - start
            text = output["text"].strip()
            row["runs"].append({"kind": "first" if index == 0 else "warm", "index": index,
                                "inference_seconds": elapsed, "text": text, "score": score(reference, text)})
        row["warm_median_seconds"] = statistics.median(r["inference_seconds"] for r in row["runs"][1:])
        row["all_transcripts_identical"] = len({r["text"] for r in row["runs"]}) == 1
        result["models"].append(row)
        args.output.parent.mkdir(parents=True, exist_ok=True)
        args.output.write_text(json.dumps(result, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
        print(json.dumps({"model": name, "load_seconds": load_seconds, "first_seconds": row["runs"][0]["inference_seconds"],
                          "warm_median_seconds": row["warm_median_seconds"], "text": row["runs"][0]["text"],
                          "score": row["runs"][0]["score"]}), flush=True)
        del model
        gc.collect()


if __name__ == "__main__":
    main()
