"""Generate speech audio from text using MiniMax TTS API."""

import os
import tempfile

import httpx

MINIMAX_API_BASE = "https://api.minimax.io"


async def handler(params: dict) -> dict:
    """Convert text to speech, return path to MP3 file."""
    text = params["text"]
    voice_id = params.get("voice_id", "Cantonese_GentleLady")
    speed = params.get("speed", 1.0)

    if not text.strip():
        raise ValueError("text cannot be empty.")

    if not (0.5 <= speed <= 2.0):
        raise ValueError(f"speed must be between 0.5 and 2.0, got {speed}.")

    api_key = os.environ.get("MINIMAX_API_KEY")
    group_id = os.environ.get("MINIMAX_GROUP_ID")
    if not api_key:
        raise ValueError("MINIMAX_API_KEY not set. Get one from https://www.minimax.io")
    if not group_id:
        raise ValueError("MINIMAX_GROUP_ID not set. Find it in your MiniMax dashboard.")

    url = f"{MINIMAX_API_BASE}/v1/t2a_v2?GroupId={group_id}"
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
    }
    payload = {
        "model": "speech-2.5-turbo-preview",
        "text": text,
        "stream": False,
        "voice_setting": {
            "voice_id": voice_id,
            "speed": speed,
            "vol": 1.0,
            "pitch": 0,
        },
        "audio_setting": {
            "sample_rate": 32000,
            "bitrate": 128000,
            "format": "mp3",
            "channel": 1,
        },
    }

    async with httpx.AsyncClient(timeout=30) as client:
        resp = await client.post(url, headers=headers, json=payload)

    if resp.status_code != 200:
        raise ValueError(f"MiniMax API error ({resp.status_code}): {resp.text[:300]}")

    result = resp.json()

    if "data" not in result or "audio" not in result.get("data", {}):
        raise ValueError(f"MiniMax returned unexpected response: {str(result)[:300]}")

    audio_hex = result["data"]["audio"]

    try:
        audio_bytes = bytes.fromhex(audio_hex)
    except ValueError as e:
        raise ValueError(f"Failed to decode MiniMax audio data: {e}") from e

    tmp = tempfile.NamedTemporaryFile(suffix=".mp3", delete=False)
    tmp.write(audio_bytes)
    tmp.close()

    return {
        "audio_file": tmp.name,
        "voice_used": voice_id,
        "audio_bytes_size": len(audio_bytes),
    }
