"""CPU/GPU inference from local model files. No outbound speech service."""
import os
import threading
from array import array
from pathlib import Path

import numpy as np


class Cancelled(Exception):
    pass


class BadAudio(ValueError):
    pass


def check_cancel(cancel: threading.Event):
    if cancel.is_set():
        raise Cancelled()


def decode_mono(path: Path, limit: int, cancel: threading.Event):
    import av
    count = 0
    samples = array("h")
    try:
        with av.open(str(path), mode="r") as container:
            if not container.streams.audio:
                raise BadAudio("Аудио суваг олдсонгүй.")
            stream = container.streams.audio[0]
            resampler = av.AudioResampler(format="s16", layout="mono", rate=16000)
            def add(frames):
                nonlocal count
                for frame in frames:
                    count += frame.samples
                    if count > limit * 16000:
                        raise BadAudio(f"Бичлэг {limit // 60} минутаас хэтэрсэн байна.")
                    samples.frombytes(frame.to_ndarray().tobytes())
            for frame in container.decode(stream):
                check_cancel(cancel)
                add(resampler.resample(frame))
            add(resampler.resample(None))
    except (Cancelled, BadAudio):
        raise
    except Exception:
        raise BadAudio("Аудиог нээж чадсангүй. Бичлэг гэмтсэн эсвэл формат дэмжигдэхгүй байна.") from None
    if not samples:
        raise BadAudio("Аудио хоосон байна.")
    return np.frombuffer(samples, dtype=np.int16).astype(np.float32) / 32768.0


class Engine:
    def __init__(self, model_path: str, device="cpu", compute_type="int8", threads=4):
        self.path = Path(model_path)
        self.device, self.compute_type, self.threads = device, compute_type, threads
        self.model = None

    @property
    def ready(self):
        return all((self.path / f).is_file() for f in ("model.bin", "tokenizer.json", "preprocessor_config.json"))

    def recognize(self, path: Path, cancel: threading.Event, max_seconds: int) -> dict:
        from faster_whisper import WhisperModel
        check_cancel(cancel)
        audio = decode_mono(path, max_seconds, cancel)
        if self.model is None:
            self.model = WhisperModel(str(self.path), device=self.device, compute_type=self.compute_type,
                                      cpu_threads=self.threads, local_files_only=True)
        check_cancel(cancel)
        duration = len(audio) / 16000.0
        output, _ = self.model.transcribe(audio, language="mn", task="transcribe", beam_size=5, vad_filter=True)
        segments = []
        for item in output:
            check_cancel(cancel)
            text = item.text.strip()
            if text:
                start = min(duration, max(0.0, float(item.start)))
                segments.append({"start": start, "end": max(start, min(duration, float(item.end))), "text": text})
        return {"text": " ".join(item["text"] for item in segments), "segments": segments, "duration": duration}


def configured_engine():
    return Engine(os.getenv("WHISPER_MODEL", "/models/whisper-small-mn-ct2"), os.getenv("WHISPER_DEVICE", "cpu"),
                  os.getenv("WHISPER_COMPUTE_TYPE", "int8"), int(os.getenv("CPU_THREADS", "4")))
