"""Score raw/*.json into results.csv (one row per engine x dataset) and per_utterance.csv.

WER: corpus-level (total edits / total reference words), jiwer 4.0.0, after the Whisper English text normaliser
(whisper-normalizer 1.0.1, a copy of openai/whisper's EnglishTextNormalizer, as used by the Hugging Face Open ASR
Leaderboard). EdAcc tags such as <LAUGH>, <OVERLAP>, <FOREIGN> are removed from references first. Also reported:
a basic WER (lowercase, punctuation stripped except apostrophes, whitespace collapsed).
Speed is the median of the two launches.
"""
import csv, glob, json, os, re, sys, statistics
import jiwer
from whisper_normalizer.english import EnglishTextNormalizer

B = sys.argv[1]
models = {m['id']: m for m in json.load(open(os.path.join(os.environ.get('JOT_REPO', '.'), 'rust/crates/jot-speech/src/local_models.json')))}
norm = EnglishTextNormalizer()
TAG = re.compile(r'<[^>]+>')

def basic(s):
    s = s.lower().replace('’', "'")
    s = re.sub(r"[^\w\s']", ' ', s)
    return ' '.join(s.split())

def wer(refs, hyps):
    pairs = [(r, h) for r, h in zip(refs, hyps) if r.strip()]
    o = jiwer.process_words([p[0] for p in pairs], [p[1] if p[1].strip() else '' for p in pairs])
    return 100 * (o.substitutions + o.deletions + o.insertions) / sum(len(p[0].split()) for p in pairs)

manifest = {(m['set'], m['id']): m for m in map(json.loads, open(os.path.join(B, 'manifest.jsonl')))}
order = ['moonshine-tiny-gguf', 'parakeet-tdt_ctc-110m-gguf', 'parakeet-unified-en-0.6b-gguf',
         'nemotron-3.5-asr-streaming-0.6b-gguf', 'whisper-medium-gguf', 'speech-transcriber']
rows, per = [], []
for name in order:
    p = os.path.join(B, 'raw', name + '.json')
    if not os.path.exists(p): continue
    d = json.load(open(p))
    m = models.get(d['model'])
    L = d['launches']
    for s in ['librispeech-test-clean', 'edacc-test', 'all']:
        def sel(launch): return [r for r in launch['rows'] if s == 'all' or r['set'] == s]
        r1 = sel(L[0])
        refs = [TAG.sub(' ', manifest[(r['set'], r['id'])]['ref']) for r in r1]
        hyps = [r['hyp'] or '' for r in r1]
        audio = sum(r['duration'] for r in r1)
        rtfs = [sum(r['seconds'] for r in sel(l)) / audio for l in L]
        same = sum(1 for a, b in zip(sel(L[0]), sel(L[1])) if a['hyp'] == b['hyp'])
        rows.append(dict(
            engine=d['model'], name=m['name'] if m else 'Apple SpeechAnalyzer (SpeechTranscriber, en-US)',
            dataset=s, utterances=len(r1), audio_minutes=round(audio / 60, 2),
            wer_whisper_norm=round(wer([norm(x) for x in refs], [norm(x) for x in hyps]), 2),
            wer_basic_norm=round(wer([basic(x) for x in refs], [basic(x) for x in hyps]), 2),
            failed_clips=sum(1 for r in r1 if r['hyp'] is None), empty_outputs=sum(1 for r in r1 if r['hyp'] is not None and not r['hyp'].strip()),
            rtf_median=round(statistics.median(rtfs), 4), rtf_launches=';'.join('%.4f' % x for x in rtfs),
            seconds_per_30s_audio=round(30 * statistics.median(rtfs), 3),
            median_clip_latency_s=round(statistics.median(statistics.median(r['seconds'] for r in sel(l)) for l in L), 3),
            identical_text_across_launches=f'{same}/{len(r1)}',
            load_seconds_first=round(L[0]['load_seconds'], 2), load_seconds_repeat=round(L[1]['load_seconds'], 2),
            first_clip_after_load_s=round(statistics.median(l['first_clip_seconds'] for l in L), 3),
            peak_memory_footprint_mb=round(max(l['peak_footprint_bytes'] for l in L) / 1e6),
            max_rss_mb=round(max(l['max_rss_bytes'] for l in L) / 1e6),
            disk_mb=round(m['size'] / 1e6) if m else '',
            backend=L[0]['backend'], language_sent=L[0]['language'],
            handy_published_en_error_percent=(m['benchmark']['accuracy'].get('en', {}).get('errorPercent', '') if m else ''),
            handy_published_seconds_per_30s=(m['benchmark'].get('secondsPer30s', '') if m else ''),
        ))
        if s != 'all':
            for r, ref, hyp in zip(r1, refs, hyps):
                per.append(dict(engine=name, set=r['set'], id=r['id'], duration=round(r['duration'], 2), seconds_launch1=round(r['seconds'], 4),
                                wer_whisper_norm=round(wer([norm(ref)], [norm(hyp)]), 2) if norm(ref).strip() else '', ref=ref.strip(), hyp=hyp))
for fn, data in [('results.csv', rows), ('per_utterance.csv', per)]:
    with open(os.path.join(B, fn), 'w', newline='') as f:
        w = csv.DictWriter(f, fieldnames=list(data[0])); w.writeheader(); w.writerows(data)
for r in rows:
    print(f"{r['name'][:34]:34} {r['dataset'][:12]:12} WER {r['wer_whisper_norm']:6} basic {r['wer_basic_norm']:6} s/30s {r['seconds_per_30s_audio']:6} "
          f"lat {r['median_clip_latency_s']:6} load {r['load_seconds_first']}/{r['load_seconds_repeat']} mem {r['peak_memory_footprint_mb']} same {r['identical_text_across_launches']} fail {r['failed_clips']}/{r['empty_outputs']}")
