#!/usr/bin/env python3
"""
Transcribe an audio file using openai-whisper on verified CUDA or CPU hardware.

stdin:  JSON {"path": "...", "model": "tiny|base|small|medium|large-v3"}
stdout: JSON {"text": "...", "duration": null, "segments": []}
        or   {"error": "<kind>", "message": "..."}

Automatic CPU is selected only when physical CUDA hardware is absent.
An explicit CPU override still requires OMNIUS_ASR_ALLOW_CPU=1.
"""
import sys, os, json, math, struct, warnings, wave, platform, re, subprocess
from pathlib import Path

warnings.filterwarnings("ignore")
os.environ.setdefault("PYTHONWARNINGS", "ignore")

PCM16_SILENCE_MAX_PEAK = 4
PCM16_SILENCE_MAX_RMS = 1.0
PCM16_ACTIVE_SAMPLE_THRESHOLD = 8


def path_exists(path):
    try:
        Path(path).stat()
        return True
    except FileNotFoundError:
        return False


def linux_cuda_hardware(pci_root="/sys/bus/pci/devices", dev_root="/dev",
                        jetson_paths=("/etc/nv_tegra_release", "/sys/module/tegra_fuse"),
                        model_path="/proc/device-tree/model", driver_path="/proc/driver/nvidia/gpus"):
    """Inspect physical inventory, never Torch availability or CUDA masks."""
    try:
        if any(path_exists(path) for path in jetson_paths):
            return "present"
        model = Path(model_path)
        if path_exists(model) and re.search(r"\b(nvidia|jetson|orin|tegra)\b", model.read_text().replace("\0", " "), re.I):
            return "present"
        nodes = list(Path(dev_root).iterdir())
        if len(nodes) > 4096:
            return "unknown"
        if any(re.match(r"^(nvidia|nvhost)|^nvmap$", path.name) for path in nodes):
            return "present"
        driver = Path(driver_path)
        if path_exists(driver) and any(driver.iterdir()):
            return "present"
        devices = list(Path(pci_root).iterdir())
        if not devices or len(devices) > 4096:
            return "unknown"
        for path in devices:
            vendor = (path / "vendor").read_text().strip().lower()
            if not re.fullmatch(r"0x[0-9a-f]{4}", vendor):
                return "unknown"
            if vendor == "0x10de":
                return "present"
        return "absent"
    except (OSError, ValueError):
        return "unknown"


def windows_cuda_hardware(env):
    try:
        result = subprocess.run(["powershell.exe", "-NoLogo", "-NoProfile", "-NonInteractive", "-Command",
            "$ErrorActionPreference='Stop'; $ids=@(Get-CimInstance Win32_PnPEntity | ForEach-Object { $_.PNPDeviceID }); "
            "@{complete=$true; ids=$ids} | ConvertTo-Json -Compress"], env=env, capture_output=True, text=True, timeout=3)
        if result.returncode or len(result.stdout) > 262144:
            return "unknown"
        inventory = json.loads(result.stdout.lstrip("\ufeff"))
        ids = inventory.get("ids")
        if inventory.get("complete") is not True or not isinstance(ids, list) or not 0 < len(ids) <= 4096 or not all(isinstance(value, str) and value for value in ids):
            return "unknown"
        return "present" if any(re.match(r"^PCI\\VEN_10DE(?:&|\\|$)", value, re.I) for value in ids) else "absent"
    except (OSError, ValueError, AttributeError, subprocess.SubprocessError):
        return "unknown"


def cuda_hardware(env):
    system = platform.system()
    if system == "Darwin":
        return "absent"
    smi = "unknown"
    try:
        result = subprocess.run(["nvidia-smi", "--query-gpu=uuid", "--format=csv,noheader"],
                                env=env, capture_output=True, text=True, timeout=3)
        lines = [line.strip() for line in result.stdout.splitlines() if line.strip()]
        if result.returncode == 0 and len(result.stdout) <= 16384:
            if lines and all(re.fullmatch(r"GPU-[a-z0-9-]+", line, re.I) for line in lines):
                return "present"
            smi = "absent" if not lines else "unknown"
        elif (result.stdout + "\n" + result.stderr).strip() == "No devices were found":
            smi = "absent"
    except FileNotFoundError:
        smi = "unavailable"
    except (OSError, subprocess.SubprocessError):
        pass
    physical = linux_cuda_hardware() if system == "Linux" else windows_cuda_hardware(env) if system == "Windows" else "unknown"
    if physical == "present":
        return "present"
    return "unknown" if smi == "unknown" else physical


def resolve_asr_device(env=None, hardware_probe=None):
    env = os.environ if env is None else env
    requested = env.get("OMNIUS_ASR_DEVICE", "auto").strip().lower() or "auto"
    if requested == "cpu":
        if env.get("OMNIUS_ASR_ALLOW_CPU", "").strip().lower() not in ("1", "true", "yes", "on"):
            raise RuntimeError("Explicit CPU ASR requires OMNIUS_ASR_ALLOW_CPU=1.")
        return "cpu", False
    if re.fullmatch(r"cuda(?::(?:0|[1-9][0-9]*))?", requested):
        return requested, False
    if requested != "auto":
        raise RuntimeError("Unsupported ASR device: " + requested)
    hardware = (hardware_probe or cuda_hardware)(env)
    return ("cpu", True) if hardware == "absent" else ("cuda", False)


def exact_pcm16_silence(path):
    """Return typed no-speech evidence for exact PCM16/16k/mono WAV only.

    This is intentionally not VAD. It reads user bytes but never rewrites,
    normalizes, decodes another media format, or instantiates Whisper.
    """
    try:
        with wave.open(path, "rb") as wav:
            if (
                wav.getcomptype() != "NONE"
                or wav.getnchannels() != 1
                or wav.getsampwidth() != 2
                or wav.getframerate() != 16000
            ):
                return None
            frames = wav.readframes(wav.getnframes())
    except (wave.Error, OSError, EOFError):
        return None
    sample_count = len(frames) // 2
    if sample_count == 0:
        metrics = {
            "sampleRateHz": 16000, "channels": 1, "bitsPerSample": 16,
            "sampleCount": 0, "durationMs": 0.0, "peakPcm16": 0,
            "rmsPcm16": 0.0, "activeSampleCount": 0, "activeSampleRatio": 0.0,
        }
    else:
        samples = struct.iter_unpack("<h", frames[: sample_count * 2])
        total_squares = 0
        peak = 0
        active = 0
        for (sample,) in samples:
            magnitude = abs(sample)
            total_squares += sample * sample
            peak = max(peak, magnitude)
            if magnitude >= PCM16_ACTIVE_SAMPLE_THRESHOLD:
                active += 1
        metrics = {
            "sampleRateHz": 16000, "channels": 1, "bitsPerSample": 16,
            "sampleCount": sample_count, "durationMs": sample_count / 16.0,
            "peakPcm16": peak, "rmsPcm16": math.sqrt(total_squares / sample_count),
            "activeSampleCount": active, "activeSampleRatio": active / sample_count,
        }
    if (
        metrics["peakPcm16"] <= PCM16_SILENCE_MAX_PEAK
        and metrics["rmsPcm16"] <= PCM16_SILENCE_MAX_RMS
        and metrics["activeSampleCount"] == 0
    ):
        return {"kind": "no_speech", "reason": "digital_silence", "text": "", "signal": metrics}
    return None


def main() -> None:
    raw = sys.stdin.read()
    try:
        data = json.loads(raw) if raw.strip() else {}
    except Exception as e:
        print(json.dumps({"error": "bad_input", "message": str(e)}))
        return

    path = data.get("path")
    if not path or not os.path.exists(path):
        print(json.dumps({"error": "file_not_found", "path": path or ""}))
        return

    no_speech = exact_pcm16_silence(path)
    if no_speech is not None:
        print(json.dumps({**no_speech, "duration": no_speech["signal"]["durationMs"] / 1000.0, "segments": []}))
        return

    model_name = data.get("model") or "tiny"
    try:
        device, automatic_cpu = resolve_asr_device()
        import whisper
        if device.startswith("cuda"):
            import torch
            if not torch.cuda.is_available() or torch.cuda.device_count() <= 0:
                raise RuntimeError(
                    f"CUDA-only ASR requested but torch cannot use CUDA "
                    f"(torch.version.cuda={getattr(torch.version, 'cuda', None)}, device_count={torch.cuda.device_count()}). "
                    "Repair CUDA/PyTorch or explicitly select an authorized CPU device. Hardware presence never triggers automatic CPU fallback."
                )
        model = whisper.load_model(model_name, device=device)
        result = model.transcribe(path, fp16=device.startswith("cuda"), condition_on_previous_text=False)
    except Exception as e:
        print(json.dumps({"error": "whisper_failed", "message": str(e)}))
        return

    text = (result.get("text") or "").strip()
    raw_segments = result.get("segments") or []
    segments = [
        {
            "start": float(s.get("start", 0.0)),
            "end": float(s.get("end", 0.0)),
            "text": (s.get("text") or "").strip(),
        }
        for s in raw_segments
    ]
    duration = float(segments[-1]["end"]) if segments else None
    print(json.dumps({"text": text, "duration": duration, "segments": segments}))


if __name__ == "__main__":
    main()
