from __future__ import annotations

import os
import tempfile
from pathlib import Path
from typing import Tuple

from imageio_ffmpeg import get_ffmpeg_exe


AUDIO_EXTS = {".wav", ".mp3", ".m4a", ".aac", ".flac", ".ogg", ".wma", ".webm"}
VIDEO_EXTS = {".mp4", ".mkv", ".mov", ".avi", ".webm", ".m4v"}


def is_supported_media(path: str) -> bool:
    ext = Path(path).suffix.lower()
    return ext in AUDIO_EXTS or ext in VIDEO_EXTS


def is_video(path: str) -> bool:
    return Path(path).suffix.lower() in VIDEO_EXTS


def extract_audio_to_wav(video_path: str) -> Tuple[str, str]:
    """
    Extracts audio from a video into a temp wav file.
    Returns (wav_path, temp_dir) - caller should delete temp_dir when done.
    """
    ffmpeg = get_ffmpeg_exe()
    temp_dir = tempfile.mkdtemp(prefix="whiscribe_")
    out_wav = os.path.join(temp_dir, "audio.wav")

    cmd = f'"{ffmpeg}" -y -i "{video_path}" -vn -ac 1 -ar 16000 "{out_wav}"'
    code = os.system(cmd)
    if code != 0 or not os.path.exists(out_wav):
        raise RuntimeError("Failed to extract audio from video using ffmpeg.")
    return out_wav, temp_dir
