import asyncio
from concurrent.futures import Future

import gradio as gr
from a2wsgi import ASGIMiddleware
from fastapi import FastAPI


def to_wsgi(asgi_app, timeout=30):
    """a2wsgi не запускає lifespan, а в ньому Gradio стартує чергу подій. Та сама функція, що в app.py бота."""
    wsgi = ASGIMiddleware(asgi_app)
    started, stop = Future(), asyncio.Event()

    async def lifespan():
        try:
            async with asgi_app.router.lifespan_context(asgi_app):
                started.set_result(True)
                await stop.wait()
        except BaseException as error:
            if not started.done():
                started.set_exception(error)
            raise

    wsgi.lifespan = asyncio.run_coroutine_threadsafe(lifespan(), wsgi.loop)
    wsgi.stop = lambda: wsgi.loop.call_soon_threadsafe(stop.set)
    started.result(timeout)
    return wsgi


def ping():
    return "Сервер відповів"


with gr.Blocks() as demo:
    button = gr.Button("Перевірити")
    answer = gr.Textbox(label="Відповідь")
    button.click(ping, None, answer)

application = to_wsgi(gr.mount_gradio_app(FastAPI(), demo, path="/"))