"""MiniMax music adapter — POST /music_generation, download audio to save."""
import json
import os
import sys

import requests


class MiniMaxMusicAdapter:
    def generate(self, prompt, config, **kwargs):
        base_url = config["base_url"].rstrip("/")
        api_key = config["api_key"]
        model = config["model"]
        out_dir = kwargs["out_dir"]
        lyrics = kwargs.get("lyrics")
        is_instrumental = kwargs.get("instrumental", False)

        endpoint = f"{base_url}/music_generation"
        headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json",
        }
        payload = {
            "model": model,
            "prompt": prompt,
            "is_instrumental": is_instrumental,
            "output_format": "url",
            "audio_setting": {
                "sample_rate": 44100,
                "bitrate": 256000,
                "format": "mp3",
            },
        }
        if lyrics:
            payload["lyrics"] = lyrics

        print(f"[minimax_music] generating with model={model}...", file=sys.stderr)
        resp = requests.post(endpoint, headers=headers, json=payload, timeout=120)
        data = resp.json()

        if data.get("base_resp", {}).get("status_code") != 0:
            raise RuntimeError(f"MiniMax error: {data.get('base_resp', {}).get('status_msg')}")

        audio_data = data.get("data", {})
        status = audio_data.get("status")
        if status == 1:
            raise RuntimeError("music still synthesizing (status=1), retry later")

        fname = kwargs.get("output_path") or os.path.join(out_dir, "music.mp3")
        audio_url = audio_data.get("audio")
        if not audio_url:
            raise RuntimeError("no audio URL in response")

        r = requests.get(audio_url, timeout=60)
        with open(fname, "wb") as f:
            f.write(r.content)

        duration_ms = data.get("extra_info", {}).get("music_duration", 0)
        print(f"[minimax_music] saved: {fname} ({duration_ms/1000:.1f}s)", file=sys.stderr)

        return [fname]
