#!/usr/bin/env python3
"""Persistent Whisper transcription worker – single subprocess, model loaded once."""

import sys
import json


def main():
    from faster_whisper import WhisperModel

    model_path = "base"
    language = "ca"
    model = None

    # Signal node that the process is alive and listening
    print(json.dumps({"type": "ready"}), flush=True)

    for line in sys.stdin:
        line = line.strip()
        if not line:
            continue

        try:
            msg = json.loads(line)
        except json.JSONDecodeError:
            continue

        if msg.get("type") == "init":
            model_path = msg.get("model", "base")
            language = msg.get("language", "ca") or "ca"
            print(f"[whisper-worker] Loading model='{model_path}' language='{language}'", file=sys.stderr, flush=True)
            model = WhisperModel(model_path, device="cpu", compute_type="int8")
            print(json.dumps({"type": "init_ok"}), flush=True)
            continue

        if msg.get("type") == "transcribe":
            audio_path = msg.get("path")
            msg_id = msg.get("msgId", "")
            if not audio_path:
                print(json.dumps({"type": "error", "text": "no path provided", "msgId": msg_id}), flush=True)
                continue

            try:
                segments, info = model.transcribe(audio_path, language=language or None)
                transcript = ""
                for seg in segments:
                    transcript += seg.text + " "
                result_text = transcript.strip()
                print(json.dumps({"type": "transcript", "text": result_text, "msgId": msg_id}), flush=True)
            except Exception as exc:
                print(json.dumps({"type": "error", "text": str(exc), "msgId": msg_id}), flush=True)


if __name__ == "__main__":
    main()
