#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Project      : AI.  @by PyCharm
# @File         : videos
# @Time         : 2025/6/11 15:13
# @Author       : betterme
# @WeChat       : meutils
# @Software     : PyCharm
# @Description  :

from meutils.pipe import *
from meutils.io.files_utils import to_url, to_base64
from meutils.decorators.retry import retrying
from meutils.apis.oneapi.utils import polling_keys

from meutils.llm.clients import AsyncClient
from meutils.schemas.openai_types import CompletionRequest
from meutils.schemas.video_types import SoraVideoRequest

from meutils.db.redis_db import redis_aclient
from meutils.llm.check_utils import check_token_for_volc
# from meutils.llm.check_utils import check_token_for_volc_with_cache as check_token_for_volc

from meutils.config_utils.lark_utils import get_next_token_for_polling, get_series

from fastapi import APIRouter, File, UploadFile, Query, Form, Depends, Request, HTTPException, status, BackgroundTasks

BASE_URL = "https://ml-platform-api.console.volcengine.com/ark/bff/api/cn-beijing/2024-01-29"


# "https://ml-platform-api.console.volcengine.com/ark/bff/api/cn-beijing/2024-01-29/CreateVideoGenTask"

class Tasks(object):

    def __init__(self, api_key):
        self.api_key = api_key

        default_headers = {
            "x-csrf-token": api_key.split("|")[0],
            "Cookie": api_key.split("|")[1]
        }
        self.client = AsyncClient(base_url=BASE_URL, default_headers=default_headers)

    def create(self, request: SoraVideoRequest):
        payload = {
            "Name": "doubao-seedance-2-0",
            "Prompt": "【图片 1】【图片 2】融合起",
            "TaskType": "BasicMode",
            "VideoTaskType": "reference_media",  #######
            "ModelName": "doubao-seedance-2-0",
            "ModelVersion": "260128",
            "Ratio": "adaptive",
            "Resolution": "480p",
            "GroupId": "1-1770730689454",
            "Duration": 5,
            "Seed": -1,
            "EndpointID": "doubao-seedance-2-0-260128",
            # "ReferenceImages": [
            #     {
            #         "BucketName": "ark-common-storage-prod-cn-beijing",
            #         "ObjectKey": "presets/experience/gen_video/materials/%E5%9B%BE%E7%89%87/%E6%9C%8D%E9%A5%B0/%E5%A4%AA%E7%A9%BA%E6%9C%8D.jpg",
            #         "Url": "https://ark-common-storage-prod-cn-beijing.tos-cn-beijing.volces.com/presets/experience/gen_video/materials/%E5%9B%BE%E7%89%87/%E6%9C%8D%E9%A5%B0/%E5%A4%AA%E7%A9%BA%E6%9C%8D.jpg",
            #         "Label": "image_1_1"
            #     },
            #     {
            #         "BucketName": "ark-common-storage-prod-cn-beijing",
            #         "ObjectKey": "presets/experience/gen_video/materials/%E5%9B%BE%E7%89%87/%E7%94%BB%E9%A3%8E/%E4%B8%99%E7%83%AF%E6%8F%92%E7%94%BB.jpg",
            #         "Url": "https://ark-common-storage-prod-cn-beijing.tos-cn-beijing.volces.com/presets/experience/gen_video/materials/%E5%9B%BE%E7%89%87/%E7%94%BB%E9%A3%8E/%E4%B8%99%E7%83%AF%E6%8F%92%E7%94%BB.jpg",
            #         "Label": "image_2_2"
            #     }
            # ],
            "GenerationTimeout": 48,
            "GenerateAudio": True,
            "DurationMode": "duration",
            "RichTextTemplatePrompt": "<<<image_1_1>>><<<image_2_2>>>融合起",
            "OptimizePromptOptions": {
                "EnableWebSearch": False
            }
        }
        ### 映射
        payload["Prompt"] = request.prompt
        payload["Duration"] = int(request.seconds or 1)

        if request.resolution:
            payload["Resolution"] = request.resolution

        if request.aspect_ratio:
            payload["Ratio"] = request.aspect_ratio

        if urls := request.input_reference:
            payload["ReferenceImages"] = [
                {
                    "BucketName": "ark-common-storage-prod-cn-beijing",
                    "ObjectKey": f"presets/experience/gen_video/materials/自定义/{i}",
                    "Url": url,
                    "Label": f"image_{i}_{i}"
                }
                for i, url in enumerate(urls, 1)
            ]

        logger.debug(bjson(payload))


        response = self.client.post("/CreateVideoGenTask", body=payload, cast_to=object)
        logger.debug(bjson(response))

        return response


# 执行异步函数
if __name__ == "__main__":
    api_key = "c30e3d49e0138937a83109a84c65c312|user_locale=zh; monitor_huoshan_web_id=7467761534115284489; monitor_session_id_flag=1; p_c_check=1; _qimei_uuid42=19c180a1723100cab20e31b701a4124555c551b916; _qimei_i_3=57ca79d3970c52d9c497aa625d8027e5a6bcf0f71a5b04d4e0872b502092276d32633f973989e28184b1; signin_i18next=zh; volcfe-uuid=0701f6f2-a611-4599-a2fc-57cb015ff828; hasUserBehavior=1; __spti=11_000JnXNrWATPtPrMwlQ3ilQxfn2UtC; __sptiho=0B11_000JnXNrWATPtPrMwlQ3ilQxfn2UtC_bEv/KoxCOM4AcC; __spti=11_000JnXNrWATPtPrMwlQ3ilQxfn2UtC; __sptiho=0B11_000JnXNrWATPtPrMwlQ3ilQxfn2UtC_bEv/KoxCOM4AcC; _tea_utm_cache_3569={%22utm_source%22:%22coopensrc%22%2C%22utm_medium%22:%22github%22%2C%22utm_campaign%22:%22doubao%22%2C%22utm_term%22:%22project%22%2C%22utm_content%22:%22aidrawio%22}; monitor_utm=%257B%2522utm_campaign%2522%253A%2522doubao%2522%252C%2522utm_content%2522%253A%2522aidrawio%2522%252C%2522utm_medium%2522%253A%2522github%2522%252C%2522utm_source%2522%253A%2522coopensrc%2522%252C%2522utm_term%2522%253A%2522project%2522%257D; _tea_utm_cache_520918={%22utm_source%22:%22coopensrc%22%2C%22utm_medium%22:%22github%22%2C%22utm_campaign%22:%22doubao%22%2C%22utm_term%22:%22project%22%2C%22utm_content%22:%22aidrawio%22}; volcengineLoginMethod=pwd; isIntranet=0; VOLCFE_im_uuid=1770641165069598896; ve_doc_history=82379%2C6269%2C6256%2C85128%2C86081%2C6348%2C85621%2C6260; referrer_title=%E6%A8%A1%E5%9E%8B%E4%BB%B7%E6%A0%BC--%E7%81%AB%E5%B1%B1%E6%96%B9%E8%88%9F%E5%A4%A7%E6%A8%A1%E5%9E%8B%E6%9C%8D%E5%8A%A1%E5%B9%B3%E5%8F%B0-%E7%81%AB%E5%B1%B1%E5%BC%95%E6%93%8E; monitor_session_id=1546773748914996048; _qimei_h38=94cee221b20e31b701a412450300000ce19c18; monitor_traceid_base_cookie=1406; digest=eyJhbGciOiJSUzI1NiIsImtpZCI6ImE5ZDM1YTQ4YmZiNDExZjA4OWMwMDAxNjNlMDcwOGJkIn0.eyJhdWQiOlsi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RlZS0yM2VjLTQ4MDktODFmZi04YjUzY2E0OTQ3N2IiLCJzc19uIjoiN096NyNxUjNtIiwidCI6IkFjY291bnQiLCJ0b3BpYyI6InNpZ25pbl91c2VyX2luZm8iLCJ2ZXJzaW9uIjoidjEiLCJ6aXAiOiIifQ.eRPfyG9wOwV8pODkcwl2H7zbWGPEjTHxlgfV_TlqZWhu9XStvhOZF5somhtFD8QvCTfpWf8pKD-HPjbTPMod_CT-z1ej8bwPJEbKpFlKhX9UeapDI39Pf0bphL-Y4ZqRb35Qlqr94JD7P1FCJTM_2obw-78d6hF2JrALgjqaIN6QGxKUR7Gds_eCCl-UcHMQueMZrtUnvCk-hHdzeUl2Z7FIdBIKaF16cuiIp05sMdKrlGEnokRatVW7kEYKqlooPA9gX772jJys8TibIknU9r5S90Q9JSmHbimJsSFK4G0Y4nKey8uKeNC_xptFzvnFddOgXkH6JDfyxMVNCPHdBw; csrfToken=c30e3d49e0138937a83109a84c65c312; csrfToken=c30e3d49e0138937a83109a84c65c312; _qimei_fingerprint=dd38b822c43601e30b795b0bb06bc28b; __tea_cache_tokens_3569={%22web_id%22:%227467761534115284489%22%2C%22user_unique_id%22:%227467761534115284489%22%2C%22timestamp%22:1770730394805%2C%22_type_%22:%22default%22}; _qimei_i_1=2cdf568b9109058ec395ff62598426e3f6bca3f1130a0783b68b2d582593206c616364c03980b1dddebcdbe0"

    request = SoraVideoRequest(
        prompt="【图片 1】【图片 2】融合起",
        seconds=5,
        resolution="480p",
        aspect_ratio="adaptive",
        # input_reference=[
        #     "https://storage.googleapis.com/falserverless/example_inputs/nano-banana-edit-input.png",
        #     "https://storage.googleapis.com/falserverless/example_inputs/nano-banana-edit-input-2.png"
        # ]
    )

    Tasks(api_key).create(request)
