import json
import logging

from fastapi import APIRouter, BackgroundTasks, HTTPException

from app.schemas.response_template import ResponseModel
from app.schemas.super_resolution import SuperResolutionModel
from app.service.super_resolution.service import SuperResolution, infer_cancel

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


@router.post("/super_resolution")
def super_resolution(request_item: SuperResolutionModel, background_tasks: BackgroundTasks):
    """
        创建一个具有以下参数的请求体:
        - **sr_image_url**: 超分图片的minio或s3 url地址
        - **sr_xn**: 超分的倍数，只接受2或4
        - **sr_tasks_id**: 任务id 用于取消超分任务和获取超分结果

        示例参数：
        {
        "sr_image_url": "aida-sys-image/images/female/blouse/0628000098.jpg",
        "sr_xn": 2,
        "sr_tasks_id": "12341556-89"
        }
    """
    try:
        logger.info(f"super_resolution request item is : @@@@@@:{json.dumps(request_item.dict())}")
        service = SuperResolution(request_item)
        background_tasks.add_task(service.sr_result)
    except Exception as e:
        logger.warning(f"super_resolution Run Exception @@@@@@:{e}")
        raise HTTPException(status_code=404, detail=str(e))
    return ResponseModel()


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