import os
import time
import urllib3
import logging
import subprocess
urllib3.disable_warnings()

from pathlib import Path
from openai import OpenAI
from app.core.config import OPENAI_API_KEY, OPENAI_TRANSCRIBE_MODEL

logger = logging.getLogger(__name__)

MAX_FILE_BYTES = 24 * 1024 * 1024  # 24MB (sedikit di bawah limit 25MB)


def compress_audio(file_path: str) -> str:
    """
    Kompres audio ke mp3 128kbps menggunakan ffmpeg.
    Mengembalikan path file hasil kompres.
    """
    output_path = str(file_path).rsplit(".", 1)[0] + "_compressed.mp3"
    try:
        subprocess.run([
            "ffmpeg", "-y",
            "-i", file_path,
            "-ar", "16000",      # sample rate 16kHz (cukup untuk speech)
            "-ac", "1",          # mono
            "-b:a", "64k",       # bitrate 64kbps
            output_path
        ], check=True, capture_output=True)
        logger.info("[compress_audio] Kompres berhasil: %s", output_path)
        return output_path
    except subprocess.CalledProcessError as e:
        logger.error("[compress_audio] ffmpeg gagal: %s", e.stderr.decode())
        raise RuntimeError("Gagal mengompres audio. Pastikan ffmpeg terinstal.")


def transcribe_api(file_path: str) -> dict:
    """
    Transkripsi audio menggunakan Whisper via KoboiLLM.
    Otomatis kompres jika file > 24MB.
    """
    api_key = OPENAI_API_KEY or os.getenv("OPENAI_API_KEY")
    if not api_key:
        raise ValueError("OPENAI_API_KEY belum diset.")

    client = OpenAI(
        api_key=api_key,
        base_url="https://api.koboillm.com/v1",
    )

    file_path = str(file_path)
    compressed_path = None

    # Kompres jika file terlalu besar
    file_size = os.path.getsize(file_path)
    if file_size > MAX_FILE_BYTES:
        logger.info(
            "[transcribe_api] File %.1fMB > 24MB, mengompres dulu...",
            file_size / 1024 / 1024
        )
        compressed_path = compress_audio(file_path)
        send_path = compressed_path
    else:
        send_path = file_path

    suffix    = Path(send_path).suffix.lower()
    mime_map  = {
        ".mp3":  "audio/mpeg",
        ".mp4":  "audio/mp4",
        ".wav":  "audio/wav",
        ".m4a":  "audio/mp4",
        ".ogg":  "audio/ogg",
        ".webm": "audio/webm",
        ".flac": "audio/flac",
        ".mpeg": "audio/mpeg",
        ".mpga": "audio/mpeg",
        ".oga":  "audio/ogg",
    }
    mime_type = mime_map.get(suffix, "audio/mpeg")
    filename  = f"audio{suffix}" if suffix else "audio.mp3"

    try:
        start = time.time()
        with open(send_path, "rb") as audio:
            transcript = client.audio.transcriptions.create(
                model=OPENAI_TRANSCRIBE_MODEL,
                file=(filename, audio, mime_type),
                response_format="verbose_json",
            )
        elapsed = round(time.time() - start, 2)
    finally:
        # Hapus file kompres sementara
        if compressed_path and os.path.exists(compressed_path):
            os.remove(compressed_path)
            logger.info("[transcribe_api] File kompres sementara dihapus.")

    return {
        "text":            transcript.text.strip(),
        "processing_time": elapsed,
        "audio_duration":  getattr(transcript, "duration", None),
    }