"""Run one engine over manifest.jsonl, twice (two separate process launches), and save raw results.

usage: bench.py BENCH_DIR tcpp MODEL_ID     (a transcribe.cpp model, through Jot's jot-transcribe worker)
       bench.py BENCH_DIR apple             (Apple SpeechAnalyzer, through Jot's speech.swift helper)
"""
import json, os, re, subprocess, sys, threading, queue, time
import numpy as np, soundfile as sf

B, ENGINE = sys.argv[1], sys.argv[2]
MODEL_ID = sys.argv[3] if len(sys.argv) > 3 else 'apple/speech-transcriber'
LAUNCHES = 2
manifest = [json.loads(l) for l in open(os.path.join(B, 'manifest.jsonl'))]
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')))}


def model_language(model, wanted='en-US'):  # local_models.rs::model_language
    langs = model['languages']
    if len(langs) == 1: return langs[0]
    base = wanted.split('-')[0].lower()
    if base in langs: return base
    return 'auto' if model['supportsLanguageDetection'] else 'en'


def native_language(advertised, language):  # local_models.rs::native_language (simplified for "en")
    if language == 'auto': return None
    for a in advertised:
        if a == language: return a
    for a in advertised:
        if a.lower().replace('_', '-').split('-')[0] == language: return a
    return language


def peak_footprint(stderr_path):
    """/usr/bin/time -l: 'peak memory footprint' (bytes) and 'maximum resident set size' (bytes)."""
    txt = open(stderr_path, errors='replace').read()
    fp = re.findall(r'(\d+)\s+peak memory footprint', txt)
    rss = re.findall(r'(\d+)\s+maximum resident set size', txt)
    return (int(fp[-1]) if fp else None), (int(rss[-1]) if rss else None)


class Proc:
    def __init__(self, argv, stderr_path):
        self.err = open(stderr_path, 'wb')
        self.p = subprocess.Popen(['/usr/bin/time', '-l'] + argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self.err)
        self.q = queue.Queue()
        threading.Thread(target=self._read, daemon=True).start()

    def _read(self):
        for line in self.p.stdout:
            try: self.q.put(json.loads(line))
            except ValueError: pass
        self.q.put(None)

    def reply(self, want_id, skip=('started',)):
        while True:
            r = self.q.get(timeout=900)
            if r is None: raise RuntimeError('engine quit')
            if r.get('id') == want_id and r.get('type') not in skip: return r

    def close(self):
        self.p.stdin.close(); self.p.wait(); self.err.close()


def run_tcpp(launch):
    model = models[MODEL_ID]
    path = os.path.join(B, 'models', model['filename'])
    errp = os.path.join(B, 'raw', f"{MODEL_ID.split('/')[1]}.launch{launch}.stderr")
    t0 = time.perf_counter()
    pr = Proc([os.path.join(B, 'bin/jot-transcribe')], errp)
    pr.p.stdin.write((json.dumps(dict(type='load', id=1, lib=os.path.join(B, 'lib'), path=path, cpu=False)) + '\n').encode()); pr.p.stdin.flush()
    loaded = pr.reply(1)
    load_s = time.perf_counter() - t0
    if loaded.get('type') != 'loaded': raise RuntimeError(loaded)
    lang = native_language(loaded['languages'], model_language(model))
    rid = [1]

    def run(wav):
        pcm, sr = sf.read(wav, dtype='float32'); assert sr == 16000
        rid[0] += 1
        hdr = dict(type='run', id=rid[0], samples=len(pcm))
        if lang: hdr['language'] = lang
        buf = (json.dumps(hdr) + '\n').encode() + pcm.astype('<f4').tobytes()
        t = time.perf_counter(); pr.p.stdin.write(buf); pr.p.stdin.flush()
        r = pr.reply(rid[0]); dt = time.perf_counter() - t
        return (r.get('text') if r.get('type') == 'text' else None), dt, r.get('error')
    return pr, errp, load_s, dict(backend=loaded['backend'], language=lang), run


def run_apple(launch):
    errp = os.path.join(B, 'raw', f'apple.launch{launch}.stderr')
    t0 = time.perf_counter()
    pr = Proc([os.path.join(B, 'bin/jot-speech-bench'), '--serve'], errp)
    rid = [1]
    pr.p.stdin.write((json.dumps(dict(id=1, locale='en-US')) + '\n').encode()); pr.p.stdin.flush()
    r = pr.reply(1)
    if 'error' in r: raise RuntimeError(r)
    load_s = time.perf_counter() - t0

    def run(wav):
        rid[0] += 1
        t = time.perf_counter()
        pr.p.stdin.write((json.dumps(dict(id=rid[0], path=wav, locale='en-US')) + '\n').encode()); pr.p.stdin.flush()
        r = pr.reply(rid[0]); dt = time.perf_counter() - t
        segs = r.get('segments')
        # Jot joins segments with a space for space-separated languages (joinSegments).
        return (' '.join(s.strip() for s in segs if s.strip()) if segs is not None else None), dt, r.get('error')
    return pr, errp, load_s, dict(backend='apple', language='en-US'), run


os.makedirs(os.path.join(B, 'raw'), exist_ok=True)
out = dict(model=MODEL_ID, engine=ENGINE, launches=[])
for launch in (1, 2):
    pr, errp, load_s, info, run = (run_tcpp if ENGINE == 'tcpp' else run_apple)(launch)
    # First clip after load (not counted in the pass): what the first dictation after a cold start pays.
    _, first_s, _ = run(manifest[0]['path'])
    rows = []
    for m in manifest:
        text, dt, err = run(m['path'])
        rows.append(dict(set=m['set'], id=m['id'], duration=m['duration'], seconds=dt, hyp=text, error=err))
    pr.close()
    fp, rss = peak_footprint(errp)
    out['launches'].append(dict(load_seconds=load_s, first_clip_seconds=first_s, peak_footprint_bytes=fp, max_rss_bytes=rss, rows=rows, **info))
    print(MODEL_ID, 'launch', launch, 'load %.2fs' % load_s, 'compute %.1fs' % sum(r['seconds'] for r in rows),
          'footprint %.0f MB' % ((fp or 0) / 1e6), 'errors', sum(1 for r in rows if r['hyp'] is None), flush=True)
json.dump(out, open(os.path.join(B, 'raw', MODEL_ID.split('/')[1] + '.json'), 'w'), indent=1)
