from nonebot_plugin_alconna import Alconna, Args, Option, UniMessage, on_alconna

from konabot.common.nb.exc import BotExceptionMessage
from konabot.plugins.sksl.run_sksl import render_sksl_shader_to_gif


cmd_run_sksl = on_alconna(Alconna(
    "shadertool",
    Option("--width", Args["width_", int]),
    Option("--height", Args["height_", int]),
    Option("--duration", Args["duration_", float]),
    Option("--fps", Args["fps_", float]),
    Args["code", str],
))

@cmd_run_sksl.handle()
async def _(
    code: str,
    width_: int = 320,
    height_: int = 180,
    duration_: float = 1.0,
    fps_: float = 15.0,
):
    if width_ <= 0 or height_ <= 0:
        raise BotExceptionMessage("长宽应该大于 0")
    if duration_ <= 0:
        raise BotExceptionMessage("渲染时长应该大于 0")
    if fps_ <= 0:
        raise BotExceptionMessage("渲染帧率应该大于 0")
    if fps_ * duration_ < 1:
        raise BotExceptionMessage("时长太短或帧率太小，没有帧被渲染")
    if fps_ * duration_ > 100:
        raise BotExceptionMessage("太多帧啦！试着缩短一点时间吧！")
    if width_ > 640 or height_ > 640:
        raise BotExceptionMessage("最大支持 640x640 啦！不要太大啦！")

    code = code.strip("\"").strip("'")

    try:
        res = await render_sksl_shader_to_gif(code, width_, height_, duration_, fps_)
        await cmd_run_sksl.send(await UniMessage().image(raw=res).export())
    except (ValueError, RuntimeError) as e:
        await cmd_run_sksl.send(await UniMessage().text(f"渲染时遇到了问题：\n\n{e}").export())
