"""Transcribe local recordings with Orukeet and a saved installation receipt.

Install: https://oruk.ai/guides/orukeet-local-transcription
Recognition uses local model files; this script makes no network requests.
"""

import argparse
import json
import sys
from pathlib import Path

from orukeet import Orukeet


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("audio", type=Path, nargs="+")
    parser.add_argument("--installation", type=Path, default=Path("installation.json"))
    args = parser.parse_args()
    if hasattr(sys.stdout, "reconfigure"):
        sys.stdout.reconfigure(encoding="utf-8")
    try:
        config = json.loads(args.installation.read_text(encoding="utf-8-sig"))
        for path in args.audio:
            if not path.is_file():
                raise FileNotFoundError(f"Audio file not found: {path}")
        # Load once. Reusing this worker avoids loading the model for every file.
        with Orukeet(config["model"], config["runtime"], device=config["device"]) as asr:
            for path in args.audio:
                result = asr.transcribe(path)
                print(json.dumps({"file": str(path), **result}, ensure_ascii=False), flush=True)
    except (OSError, ValueError, KeyError, RuntimeError) as exc:
        print(f"Transcription failed: {exc}", file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
