"""MiniMax video adapter — POST /video_generation, poll status, download via file_id.
Supports both Text-to-Video and Image-to-Video modes."""
import json
import os
import sys
import time

import requests


class MiniMaxVideoAdapter:
    # 轮询间隔和超时
    POLL_INTERVAL = 10   # 每 10 秒查一次
    MAX_WAIT = 600       # 最长等 10 分钟

    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"]

        headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json",
        }

        # ═══ Step 1: 提交生成任务 ═══
        payload = {
            "model": model,
        }
        # prompt（图生视频时可选，文生视频时必填）
        if prompt:
            payload["prompt"] = prompt
        # 图生视频模式：传入首帧图片
        if kwargs.get("first_frame_image"):
            payload["first_frame_image"] = kwargs["first_frame_image"]
        # 可选参数
        if kwargs.get("duration"):
            payload["duration"] = int(kwargs["duration"])
        if kwargs.get("resolution"):
            payload["resolution"] = kwargs["resolution"]
        if kwargs.get("prompt_optimizer") is not None:
            payload["prompt_optimizer"] = kwargs["prompt_optimizer"]

        mode = "图生视频" if "first_frame_image" in payload else "文生视频"
        print(f"[minimax_video] 提交{mode}任务 model={model}...", file=sys.stderr)
        resp = requests.post(
            f"{base_url}/video_generation",
            headers=headers,
            json=payload,
            timeout=60,
        )
        resp.raise_for_status()
        data = resp.json()

        # 检查业务错误
        base_resp = data.get("base_resp", {})
        if base_resp.get("status_code", 0) != 0:
            raise RuntimeError(f"MiniMax error: {base_resp.get('status_msg')}")

        task_id = data.get("task_id")
        if not task_id:
            raise RuntimeError(f"未返回 task_id: {data}")

        print(f"[minimax_video] task_id={task_id}, 开始轮询...", file=sys.stderr)

        # ═══ Step 2: 轮询任务状态 ═══
        file_id = None
        elapsed = 0
        while elapsed < self.MAX_WAIT:
            time.sleep(self.POLL_INTERVAL)
            elapsed += self.POLL_INTERVAL

            query_resp = requests.get(
                f"{base_url}/query/video_generation",
                headers={"Authorization": f"Bearer {api_key}"},
                params={"task_id": task_id},
                timeout=30,
            )
            query_resp.raise_for_status()
            qdata = query_resp.json()
            status = qdata.get("status", "")
            print(f"[minimax_video] 轮询 {elapsed}s: status={status}", file=sys.stderr)

            if status == "Success":
                file_id = qdata.get("file_id")
                break
            elif status == "Fail":
                err_msg = qdata.get("error_message", "未知错误")
                raise RuntimeError(f"视频生成失败: {err_msg}")
            # Processing / Queueing → 继续等

        if not file_id:
            raise RuntimeError(f"视频生成超时 ({self.MAX_WAIT}s), task_id={task_id}")

        print(f"[minimax_video] 生成完成 file_id={file_id}, 下载中...", file=sys.stderr)

        # ═══ Step 3: 获取下载 URL 并下载 ═══
        file_resp = requests.get(
            f"{base_url}/files/retrieve",
            headers={"Authorization": f"Bearer {api_key}"},
            params={"file_id": file_id},
            timeout=30,
        )
        file_resp.raise_for_status()
        download_url = file_resp.json()["file"]["download_url"]

        fname = kwargs.get("output_path") or os.path.join(out_dir, "video.mp4")
        r = requests.get(download_url, timeout=300)
        r.raise_for_status()
        with open(fname, "wb") as f:
            f.write(r.content)

        print(f"[minimax_video] 已保存: {fname}", file=sys.stderr)
        return [fname]
