import json
import logging

import requests
from fastapi import APIRouter, BackgroundTasks, HTTPException

from app.core.config import COMFYUI_SERVER_ADDRESS
from app.schemas.comfyui_i2v import ComfyuiI2VModel, ComfyuiFLF2VModel
from app.schemas.pose_transform import PoseTransformModel
from app.schemas.response_template import ResponseModel
from app.service.comfyui_I2V.flf2v_server import ComfyUIServerFLF2V
from app.service.comfyui_I2V.i2v_server import ComfyUIServerI2V
from app.service.comfyui_I2V.pose2v_server import ComfyUIServerPose2V
from app.service.generate_image.service_pose_transform import PoseTransformService, infer_cancel as pose_transform_infer_cancel

router = APIRouter()
logger = logging.getLogger()


@router.post("/pose_transform")
def pose_transform(request_item: PoseTransformModel, background_tasks: BackgroundTasks):
    """
        创建一个具有以下参数的请求体:
        - **tasks_id**: 任务id 用于取消生成任务和获取生成结果
        - **image_url**: 被生成图片的S3或minio url地址
        - **pose_id**: 1


        示例参数：
        {
          "tasks_id": "123-89",
          "image_url": "aida-results/result_0000b606-1902-11ef-9424-0242ac180002.png",
          "pose_id": "1"
        }
    """
    try:
        logger.info(f"pose_transform request item is : @@@@@@:{json.dumps(request_item.dict())}")
        service = PoseTransformService(request_item)
        background_tasks.add_task(service.get_result)
    except Exception as e:
        logger.warning(f"pose_transform Run Exception @@@@@@:{e}")
        raise HTTPException(status_code=404, detail=str(e))
    return ResponseModel()


@router.get("/pose_transform_cancel/{tasks_id}")
def pose_transform_cancel(tasks_id: str):
    try:
        logger.info(f"pose_transform_cancel request item is : @@@@@@:{tasks_id}")
        data = pose_transform_infer_cancel(tasks_id)
        logger.info(f"pose_transform_cancel response @@@@@@:{data}")
    except Exception as e:
        logger.warning(f"pose_transform_cancel Run Exception @@@@@@:{e}")
        raise HTTPException(status_code=404, detail=str(e))
    return ResponseModel(data=data['data'])


"""
骨架 + 产品图 => 视频
"""


@router.post("/comfyui_image_pose_2_video")
def comfyui_image_pose_2_video(request_item: PoseTransformModel, background_tasks: BackgroundTasks):
    """
        创建一个具有以下参数的请求体:
        - **tasks_id**: 任务id 用于取消生成任务和获取生成结果
        - **image_url**: 被生成图片的S3或minio url地址
        - **pose_id**: 1


        示例参数：
        {
          "tasks_id": "123-89",
          "image_url": "aida-results/result_0000b606-1902-11ef-9424-0242ac180002.png",
          "pose_id": "1"
        }
    """
    try:
        logger.info(f"image_pose_2_video request item is : @@@@@@:{json.dumps(request_item.dict())}")
        service = ComfyUIServerPose2V(request_item)
        background_tasks.add_task(service.get_result)
    except Exception as e:
        logger.warning(f"image_pose_2_video Run Exception @@@@@@:{e}")
        raise HTTPException(status_code=404, detail=str(e))
    return ResponseModel()


"""
产品图 + 文 => 视频
"""


@router.post("/comfyui_image_2_video")
def comfyui_image_2_video(request_item: ComfyuiI2VModel, background_tasks: BackgroundTasks):
    """
        创建一个具有以下参数的请求体:
        - **tasks_id**: 任务id 用于取消生成任务和获取生成结果
        - **image_url**: 被生成图片的S3或minio url地址
        - **prompt**: 动作表述

        示例参数：
        {
          "tasks_id": "12222515151123-89111",
          "image_url": "aida-users/89/product_image/a6949500-2393-42ac-8723-440b5d5da2b2-0-89.png",
          "prompt": "Model executing a series of poses, dynamic camera movement alternating between detailed close-ups and full shots."
        }
    """
    try:
        logger.info(f"image_2_video request item is : @@@@@@:{json.dumps(request_item.dict())}")
        service = ComfyUIServerI2V(request_item)
        background_tasks.add_task(service.get_result)
    except Exception as e:
        logger.warning(f"image_2_video Run Exception @@@@@@:{e}")
        raise HTTPException(status_code=404, detail=str(e))
    return ResponseModel()


"""
首尾帧 + 文 => 视频
"""


@router.post("/comfyui_flf_2_video")
def comfyui_flf_2_video(request_item: ComfyuiFLF2VModel, background_tasks: BackgroundTasks):
    """
        创建一个具有以下参数的请求体:
        - **tasks_id**: 任务id 用于取消生成任务和获取生成结果
        - **start_image_url**: 首帧
        - **end_image_url**: 尾帧
        - **prompt**: 动作描述

        示例参数：
        {
          "tasks_id": "202511051619-89111",
          "start_image_url": "test/start.png",
          "end_image_url": "test/end.png",
          "prompt": "Model executing a series of poses, dynamic camera movement alternating between detailed close-ups and full shots."
        }
    """
    try:
        logger.info(f"flf_2_video request item is : @@@@@@:{json.dumps(request_item.dict())}")
        service = ComfyUIServerFLF2V(request_item)
        background_tasks.add_task(service.get_result)
    except Exception as e:
        logger.warning(f"flf_2_video Run Exception @@@@@@:{e}")
        raise HTTPException(status_code=404, detail=str(e))
    return ResponseModel()


@router.get("/comfyui_i_2_video_cancel/{tasks_id}")
def comfyui_i_2_video_cancel(tasks_id: str):
    try:
        logger.info(f"comfyui_i_2_video_cancel request item is : @@@@@@:{tasks_id}")
        response = requests.post(
            f"http://{COMFYUI_SERVER_ADDRESS}/interrupt",
            json={"prompt_id": tasks_id}
        )
        data = {}
        if response.status_code == 200:
            data['data']['message'] = "任务已成功中断"
        else:
            data['data']['message'] = f"中断失败：{response.text}"
        logger.info(f"comfyui_i_2_video_cancel response @@@@@@:{data}")
    except Exception as e:
        logger.warning(f"comfyui_i_2_video_cancel Run Exception @@@@@@:{e}")
        raise HTTPException(status_code=404, detail=str(e))
    return ResponseModel(data=data['data'])
