import io
import json
import logging
import time

from PIL import ImageEnhance
from fastapi import APIRouter, HTTPException

from app.schemas.brighten import BrightenModel
from app.schemas.response_template import ResponseModel
from app.service.utils.oss_client import oss_get_image, oss_upload_image

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


def increase_brightness(img, factor):
    enhancer = ImageEnhance.Brightness(img)
    bright_img = enhancer.enhance(factor)
    return bright_img


@router.post("/brighten")
async def brighten(request_item: BrightenModel):
    """
        创建一个具有以下参数的请求体:
        - **image_url**: 提亮图片url
        - **brighten_value**: 提高亮度的比重  亮度因子 1.0 表示原始亮度，1.5 表示增加 50% 的亮度

        示例参数：
        {
        "image_url": "aida-users/89/relight_image/3850e17b-3efd-4597-90ef-2a7bcd1a1a0b-0-89.png",
        "brighten_value": 1.5
        }
    """
    try:
        start_time = time.time()
        logger.info(f"brighten request item is : @@@@@@:{json.dumps(request_item.dict())}")
        image = oss_get_image(bucket=request_item.image_url.split('/')[0], object_name=request_item.image_url[request_item.image_url.find('/') + 1:], data_type="PIL")
        new_image = increase_brightness(image, request_item.brighten_value)
        image_data = io.BytesIO()
        new_image.save(image_data, format='PNG')
        image_data.seek(0)
        image_bytes = image_data.read()
        req = oss_upload_image(bucket=request_item.image_url.split('/')[0], object_name=request_item.image_url[request_item.image_url.find('/') + 1:], image_bytes=image_bytes)
        brighten_url = f"{req.bucket_name}/{req.object_name}"
        logger.info(f"run time is : {time.time() - start_time}")
    except Exception as e:
        logger.warning(f"brighten Run Exception @@@@@@:{e}")
        raise HTTPException(status_code=404, detail=str(e))
    return ResponseModel(data=brighten_url)


if __name__ == '__main__':
    request_item = BrightenModel(image_url="aida-users/89/relight_image/3850e17b-3efd-4597-90ef-2a7bcd1a1a0b-0-89.png",
                                 brighten_value=1.5)
    image = oss_get_image(bucket=request_item.image_url.split('/')[0], object_name=request_item.image_url[request_item.image_url.find('/') + 1:], data_type="PIL")
    new_image = increase_brightness(image, request_item.brighten_value)
    new_image.show()
