#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Project      : AI.  @by PyCharm
# @File         : run_delay_tasks
# @Time         : 2026/2/16 13:39
# @Author       : betterme
# @WeChat       : meutils
# @Software     : PyCharm
# @Description  : 

from meutils.pipe import *

from meutils.db.redis_db import redis_aclient
from meutils.apis.volcengine_apis import videos_nx
from meutils.schemas.video_types import SoraVideoRequest, Video

from meutils.apis.videos.videos import OpenAIVideos  # todo

from meutils.apis.oneapi.tasks import get_tasks


async def create(api_key: Optional[str] = None):
    remote_task_ids = []

    task_ids = await get_tasks(platform="", channel_id="21496", status="UNFINISHED", return_ids=True)
    logger.debug(f"任务数量: {len(task_ids)}")

    if not api_key: return task_ids

    for task_id in task_ids:
        if request := await redis_aclient.get(f"request:{task_id}"):
            request = SoraVideoRequest.model_validate_json(request)

            # 创建任务
            # if any(i in str(e) for i in ["NotLogin", "QuotaExceeded"]):
            video = await videos_nx.Tasks(api_key).create(request)
            remote_task_ids.append(video.id)

    return remote_task_ids


async def get(task_id, api_key: Optional[str] = None):
    if isinstance(task_id, list):
        return asyncio.gather(*map(get, task_id))

    # 获取任务
    if api_key:
        video = await videos_nx.Tasks(api_key).get(task_id)
        if video.status in ["completed", "failed"]:  # 监听 写入 redis
            await redis_aclient.set(f"response:{task_id}", video.model_dump_json(exclude_none=True), ex=3600)
    else:
        video = Video(id=task_id, status="failed", error="测试队列")
        video = Video(id=task_id, status="failed")

        # await redis_aclient.set(f"response:{task_id}", video.model_dump_json(), ex=3600)

        await redis_aclient.set(f"delay::{task_id}", video.model_dump_json(), ex=3600)

if __name__ == '__main__':
    api_key = None
    # api_key = "csrfToken="
    # task_ids = arun(create(api_key))

    task_ids = ['delay::XhUYSMpNyPvqWFzVfaQCxe',
                'delay::rCMUxQSrUroARkUSSvyCDG',
                'delay::sirzdtUoFZmyvsT9vyDXrq',
                'delay::PknD5itEEwodJn9sopCmDk',
                'delay::G7enqA6VcRLH6ZvFY9UY8D',
                'delay::bcYAp3Rn4zxNwVVVXjNaQT',
                'delay::U6Yzc6VMAPKprFSrhzuRhD',
                'delay::RwkL24KQjYTc4fTqRnACLP',
                'delay::tD3iisaXZasWcHUmTSUTsk',
                'delay::uhgWFp2v7vZkrKYRb6nqPn']
    task_ids = "delay::uhgWFp2v7vZkrKYRb6nqPn"
    task_ids = "delay::tD3iisaXZasWcHUmTSUTsk"
    arun(get(task_ids))
