import os
import sys
import asyncio
import threading
import logging

APP_DIR = os.path.dirname(os.path.abspath(__file__))
os.chdir(APP_DIR)
if APP_DIR not in sys.path:
    sys.path.insert(0, APP_DIR)

log = logging.getLogger("webhook")

import main as bot_module

bot_client = bot_module.app

from flask import Flask, request
import admin_panel
flask_app = admin_panel.app


def _run_async(coro):
    try:
        loop = asyncio.get_running_loop()
    except RuntimeError:
        loop = None

    if loop and loop.is_running():
        import concurrent.futures
        with concurrent.futures.ThreadPoolExecutor() as pool:
            return pool.submit(asyncio.run, coro).result(timeout=30)
    else:
        return asyncio.run(coro)


@flask_app.route("/webhook", methods=["POST"])
def webhook():
    try:
        data = request.get_json(force=True)
        updates = data if isinstance(data, list) else [data]

        for item in updates:
            update = bot_client._parse_update(item)
            if update:
                _run_async(bot_client.process_update(update))
    except Exception as e:
        log.error(f"Webhook error: {e}")

    return "OK", 200


async def _start_bot():
    await bot_client.start()
    log.info("Bot client started")
    WEBHOOK_URL = os.environ.get("WEBHOOK_URL", "")
    if WEBHOOK_URL:
        await bot_client.update_bot_endpoints(WEBHOOK_URL, "url")
        log.info(f"Webhook registered: {WEBHOOK_URL}")
    asyncio.create_task(bot_module.process_broadcast_queue())
    while True:
        await asyncio.sleep(3600)


def _run_bot():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.run_until_complete(_start_bot())


t = threading.Thread(target=_run_bot, daemon=True)
t.start()

application = flask_app
