"""
千问视频解析工具

通过阿里云百炼平台（DashScope 兼容模式）调用 qwen3.7-plus 模型，解析视频内容。
"""
from __future__ import annotations

import asyncio
import json
import logging
import os
import time
from typing import Optional

from dotenv import load_dotenv
from openai import OpenAI

from supply_agent.paths import find_project_root
from supply_agent.tools import tool

logger = logging.getLogger(__name__)

# DASHSCOPE_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
DASHSCOPE_BASE_URL = "https://llm-33b86fznnpci2exm.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"
DEFAULT_MODEL = "qwen3.7-plus"
DEFAULT_PROMPT = "描述这段视频的内容"
DEFAULT_FPS = 2.0
DEFAULT_TIMEOUT = 120.0

_env_loaded = False


def _ensure_env_loaded() -> None:
    """从项目根目录加载 .env，使 os.getenv 能读到其中的变量。"""
    global _env_loaded
    if _env_loaded:
        return
    load_dotenv(find_project_root() / ".env")
    _env_loaded = True


def _get_client() -> OpenAI:
    _ensure_env_loaded()
    api_key = os.getenv("DASHSCOPE_API_KEY")
    if not api_key:
        raise ValueError("未设置环境变量 DASHSCOPE_API_KEY")
    return OpenAI(api_key=api_key, base_url=DASHSCOPE_BASE_URL)


def _analyze_video_sync(
    video_url: str,
    prompt: str,
    fps: float,
    model: str,
    timeout: float,
) -> str:
    client = _get_client()
    completion = client.chat.completions.create(
        model=model,
        messages=[
            {
                "role": "user",
                "content": [
                    {
                        "type": "video_url",
                        "video_url": {"url": video_url},
                        "fps": fps,
                    },
                    {"type": "text", "text": prompt},
                ],
            }
        ],
        timeout=timeout,
    )
    return completion.choices[0].message.content or ""


def _success_result(
    video_url: str,
    prompt: str,
    content: str,
    model: str,
    duration_ms: int,
) -> str:
    payload = {
        "title": "视频解析结果",
        "video_url": video_url,
        "prompt": prompt,
        "model": model,
        "content": content,
        "output": content,
        "duration_ms": duration_ms,
    }
    return json.dumps(payload, ensure_ascii=False)


def _error_result(error: str, *, title: str = "视频解析失败") -> str:
    return json.dumps({"error": error, "title": title}, ensure_ascii=False)


@tool
async def qwen_video_analyze(
    video_url: str,
    prompt: str = DEFAULT_PROMPT,
    fps: float = DEFAULT_FPS,
    model: str = DEFAULT_MODEL,
    timeout: Optional[float] = None,
) -> str:
    """
    千问视频内容解析

    通过阿里云百炼平台调用 qwen3.7-plus 模型，分析视频 URL 并返回文字描述。
    需要设置环境变量 DASHSCOPE_API_KEY。

    Args:
        video_url: 视频地址（需公网可访问的 mp4 等格式）
        prompt: 解析提示词，默认 "描述这段视频的内容"
        fps: 视频抽帧频率，默认 2（每秒采样 2 帧）
        model: 模型名称，默认 "qwen3.7-plus"
        timeout: 请求超时时间（秒），默认 120

    Returns:
        JSON 字符串，包含 content（解析文本）和 output（同 content，供 LLM 阅读）。
    """
    start_time = time.time()
    request_timeout = timeout if timeout is not None else DEFAULT_TIMEOUT

    try:
        content = await asyncio.to_thread(
            _analyze_video_sync,
            video_url,
            prompt,
            fps,
            model,
            request_timeout,
        )

        duration_ms = int((time.time() - start_time) * 1000)
        logger.info(
            "qwen_video_analyze completed: video_url=%s model=%s duration_ms=%d",
            video_url,
            model,
            duration_ms,
        )
        return _success_result(video_url, prompt, content, model, duration_ms)

    except ValueError as e:
        logger.error("qwen_video_analyze config error: %s", e)
        return _error_result(str(e))
    except Exception as e:
        logger.error(
            "qwen_video_analyze error: video_url=%s error=%s",
            video_url,
            e,
            exc_info=True,
        )
        return _error_result(str(e))


async def main() -> None:
    test_url = os.getenv("TEST_VIDEO_URL", "https://www.douyin.com/aweme/v1/play/?video_id=v0200fg10000d4lbj67og65hqvt943u0&ratio=1080p&line=0")
    # test_url = os.getenv("TEST_VIDEO_URL", "http://rescdn.yishihui.com/longvideo/transcode/video/vpc/20260713/b2507233bc8fe040003d19b34c2c7d73.mp4")

    result_json = await qwen_video_analyze(video_url=test_url)
    result = json.loads(result_json)
    if "error" in result:
        print(f"解析失败: {result['error']}")
    else:
        print(result["content"])


if __name__ == "__main__":
    asyncio.run(main())
