<filename>app/handlers/inline/plot.py
import logging
import math

import numpy as np
from aiogram.types import InlineQuery, InlineQueryResultPhoto

from app.handlers.inline.utils import annotation_answer, get_photo_link
from app.handlers.users.mathematics.plot import draw_plot
from app.loader import dp
from app.utils.math import forbidden_phrase


@dp.inline_handler(inline_modules=("plot", "y"))
async def plot_inline(inline_query: InlineQuery, inline_args: str):
    if forbidden_phrase(inline_args):
        return await annotation_answer("Недопустимое выражение")

    query = inline_args.removeprefix("y=")
    try:
        x = np.linspace(-10, 10, 100)
        buf = draw_plot(x, lambda x_: eval(query, {
            '__builtins__': {},
            'x': x_,
            'sin': np.sin,
            'cos': np.cos,
            'tan': np.tan,
            'lg': np.log,
            'log': np.log,
            'sqrt': np.sqrt,
            'math': math
        }, {}))
    except Exception as exp:
        logging.error(
            f'[MATH-PLOT-EXCEPTION] - <{exp}> [inline-{inline_query.from_user.id}]: ({inline_args})'
        )
        return await annotation_answer(f'Произошла ошибка [{exp}]')
    else:
        url = await get_photo_link(buf)
        return await inline_query.answer(
            [InlineQueryResultPhoto(
                id=f"{inline_args}-{inline_query.from_user.id}",
                photo_url=url,
                thumb_url=url
            )],
            switch_pm_text=f"Построен график y={query}", switch_pm_parameter="plot",
            # cache_time=30
        )
