import os, sys, json, asyncio

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

from config.settings import WEBHOOK_PATH, WEBHOOK_SECRET
from services.logger import setup_logging

logger = setup_logging()
_application = None


def get_loop():
    try:
        loop = asyncio.get_event_loop()
        if loop.is_closed():
            raise RuntimeError("loop closed")
        return loop
    except RuntimeError:
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        return loop


def get_application():
    global _application
    if _application is None:
        from bot_app import build_application
        app = build_application()
        loop = get_loop()
        loop.run_until_complete(app.initialize())
        if app.post_init:
            loop.run_until_complete(app.post_init(app))
        _application = app
        logger.info("Application initialized for webhook")
    return _application


def application(environ, start_response):
    method = environ.get("REQUEST_METHOD", "GET")
    path = environ.get("PATH_INFO", "") or "/"

    if method == "GET":
        start_response("200 OK", [("Content-Type", "text/plain; charset=utf-8")])
        return [b"Bot Webhook OK\n"]

    expected = WEBHOOK_PATH.rstrip("/") or "/webhook"
    if method != "POST" or not (path.rstrip("/") == expected or path.endswith(expected)):
        start_response("404 Not Found", [("Content-Type", "text/plain")])
        return [b"Not Found"]

    if WEBHOOK_SECRET:
        incoming = environ.get("HTTP_X_TELEGRAM_BOT_API_SECRET_TOKEN", "")
        if incoming != WEBHOOK_SECRET:
            logger.warning("Webhook secret mismatch")
            start_response("403 Forbidden", [("Content-Type", "text/plain")])
            return [b"Forbidden"]

    try:
        try:
            length = int(environ.get("CONTENT_LENGTH", 0) or 0)
        except ValueError:
            length = 0
        body = environ["wsgi.input"].read(length) if length > 0 else b"{}"
        update_data = json.loads(body.decode("utf-8"))

        app = get_application()
        loop = get_loop()
        from telegram import Update
        update = Update.de_json(update_data, app.bot)
        loop.run_until_complete(app.process_update(update))

        start_response("200 OK", [("Content-Type", "text/plain")])
        return [b"OK"]
    except Exception as e:
        logger.exception("Webhook error: %s", e)
        start_response("500 Internal Server Error", [("Content-Type", "text/plain")])
        return [b"Error"]
