"""
webapp.py - the bot server for ALL reseller bots (cPanel "Setup Python App", Passenger/WSGI).

How it works
  * Telegram posts every update of every reseller bot to  https://<this app>/hook/<bot_id>/<secret>
  * We ask your website (bot-api.php) which token / admin / secret belongs to that bot_id and
    check the secret, then hand the update to Main.py's handlers in a background asyncio loop.
  * Each bot has its own folder + database:  data/bots/<bot_id>/Cuibcc.db

Settings (cPanel -> Setup Python App -> Environment variables, or bot_server_config.json):
  SITE_BASE_URL   https://your-store-site.com        (no trailing slash)
  BOT_API_SECRET  the secret created in admin-bots.php
"""
import asyncio
import hmac
import json
import logging
import os
import sys
import threading
import time
import urllib.error
import urllib.parse
import urllib.request

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

log = logging.getLogger("botserver")

CACHE_SECONDS = 60        # how long admin id / token are trusted before asking the site again
NEGATIVE_SECONDS = 30     # unknown / stopped bots are not re-checked more often than this
SEEN_EVERY = 300          # heartbeat to the site (seconds)
ERROR_EVERY = 60

# ----------------------------------------------------------------------------- settings

def _cfg():
    c = {"site_base_url": os.environ.get("SITE_BASE_URL", ""), "api_secret": os.environ.get("BOT_API_SECRET", "")}
    f = os.path.join(BASE, "bot_server_config.json")
    if os.path.isfile(f):
        try:
            j = json.load(open(f, encoding="utf-8"))
            for k in ("site_base_url", "api_secret"):
                if not c[k] and j.get(k):
                    c[k] = str(j[k])
        except Exception as e:  # noqa
            log.error("bad bot_server_config.json: %s", e)
    c["site_base_url"] = c["site_base_url"].rstrip("/")
    return c


def _site_call(params: dict) -> dict:
    """Blocking call to the website's bot-api.php. Always returns a dict with 'ok'."""
    c = _cfg()
    if not c["site_base_url"] or not c["api_secret"]:
        return {"ok": False, "error": "server_not_configured"}
    url = c["site_base_url"] + "/bot-api.php?" + urllib.parse.urlencode(params)
    req = urllib.request.Request(url, headers={"X-Bot-Secret": c["api_secret"], "User-Agent": "Mozilla/5.0 (BotServer)"})
    try:
        with urllib.request.urlopen(req, timeout=10) as r:
            return json.loads(r.read().decode("utf-8"))
    except urllib.error.HTTPError as e:
        try:
            return json.loads(e.read().decode("utf-8"))
        except Exception:
            return {"ok": False, "error": "http_%s" % e.code}
    except Exception as e:
        return {"ok": False, "error": "network", "detail": str(e)[:120]}

# ----------------------------------------------------------------------------- loop + core

_loop = asyncio.new_event_loop()


def _run_loop():
    asyncio.set_event_loop(_loop)
    _loop.run_forever()


threading.Thread(target=_run_loop, name="bot-loop", daemon=True).start()

_core = None
_core_error = ""
try:
    import Main as _core_module  # noqa  (the store bot code: handlers are registered on import)
    _core = _core_module
except Exception as e:  # keep the web app alive so the error can be read in the log
    _core_error = "%s: %s" % (type(e).__name__, e)
    log.exception("Could not import Main.py")

import tenant  # noqa: E402


def _make_bot(token):
    from aiogram import Bot
    from aiogram.client.default import DefaultBotProperties
    return Bot(token=token, default=DefaultBotProperties(parse_mode="HTML"))


def _make_update(data, bot):
    from aiogram.types import Update
    return Update.model_validate(data, context={"bot": bot})

# ----------------------------------------------------------------------------- tenants

class Tenant:
    def __init__(self, bot_id, token, admin_id, secret, username):
        self.bot_id = bot_id
        self.token = token
        self.admin_id = admin_id
        self.secret = secret
        self.username = username
        self.bot = None
        self.db_path = os.path.join(BASE, "data", "bots", str(bot_id), "Cuibcc.db")
        self.loaded_at = time.time()
        self.ready = False
        self.last_seen = 0.0
        self.last_error = 0.0


_tenants = {}
_negative = {}
_lock = None  # asyncio.Lock, created inside the loop


def _prepare_db(t: Tenant):
    os.makedirs(os.path.dirname(t.db_path), exist_ok=True)
    tenant.use(t.bot, t.admin_id, t.db_path, t.username)
    _core.init_db()
    _core.migrate_categories()
    t.ready = True


async def _close_bot(t):
    try:
        if t and t.bot is not None:
            await t.bot.session.close()
    except Exception:
        pass


async def get_tenant(bot_id: int):
    global _lock
    if _lock is None:
        _lock = asyncio.Lock()
    async with _lock:
        now = time.time()
        t = _tenants.get(bot_id)
        if t and now - t.loaded_at < CACHE_SECONDS:
            return t
        if not t and now - _negative.get(bot_id, 0) < NEGATIVE_SECONDS:
            return None

        data = await _loop.run_in_executor(None, _site_call, {"action": "bot", "bot_id": bot_id})
        if not data.get("ok"):
            if data.get("error") in ("not_active", "not_found", "disabled", "unauthorized"):
                old = _tenants.pop(bot_id, None)
                await _close_bot(old)
                _negative[bot_id] = now
                return None
            if t:                                  # site hiccup: keep working, retry in 30 s
                t.loaded_at = now - CACHE_SECONDS + 30
                return t
            _negative[bot_id] = now
            return None

        token = str(data.get("token", ""))
        admin_id = int(data.get("admin_id", 0))
        secret = str(data.get("hook_secret", ""))
        uname = str(data.get("username", ""))
        if not token or not admin_id or not secret:
            _negative[bot_id] = now
            return None

        if t and t.token == token:
            t.admin_id, t.secret, t.username, t.loaded_at = admin_id, secret, uname, now
            return t

        await _close_bot(t)
        nt = Tenant(bot_id, token, admin_id, secret, uname)
        nt.bot = _make_bot(token)
        _prepare_db(nt)
        _tenants[bot_id] = nt
        log.info("bot %s (@%s) loaded", bot_id, uname)
        return nt


async def accept(bot_id: int, path_secret: str, header_secret: str):
    """Phase 1 (the HTTP request waits for it): is this update really from Telegram for this bot?"""
    if _core is None:
        return None
    t = await get_tenant(bot_id)
    if t is None:
        return None
    if not (hmac.compare_digest(header_secret or "", t.secret) and hmac.compare_digest(path_secret or "", t.secret)):
        return None
    return t


async def dispatch(t: Tenant, data: dict):
    """Phase 2 (runs after Telegram already got its 200)."""
    try:
        tenant.use(t.bot, t.admin_id, t.db_path, t.username)
        update = _make_update(data, t.bot)
        await _core.dp.feed_update(t.bot, update)
    except Exception as e:
        log.exception("update failed for bot %s", t.bot_id)
        now = time.time()
        if now - t.last_error > ERROR_EVERY:
            t.last_error = now
            msg = ("%s: %s" % (type(e).__name__, e))[:200]
            await _loop.run_in_executor(None, _site_call, {"action": "error", "bot_id": t.bot_id, "msg": msg})
        return
    now = time.time()
    if now - t.last_seen > SEEN_EVERY:
        t.last_seen = now
        await _loop.run_in_executor(None, _site_call, {"action": "seen", "bot_id": t.bot_id})

# ----------------------------------------------------------------------------- WSGI

def _reply(start_response, status, body, ctype="text/plain; charset=utf-8"):
    if isinstance(body, str):
        body = body.encode("utf-8")
    start_response(status, [("Content-Type", ctype), ("Content-Length", str(len(body)))])
    return [body]


def application(environ, start_response):
    method = environ.get("REQUEST_METHOD", "GET")
    parts = [p for p in environ.get("PATH_INFO", "").split("/") if p]

    if method != "POST":
        # health check: opening the app URL in a browser
        if _core is None:
            return _reply(start_response, "500 Internal Server Error", "Main.py could not be loaded: " + _core_error)
        return _reply(start_response, "200 OK", "bot server ok - bots loaded: %d" % len(_tenants))

    if len(parts) < 3 or parts[-3] != "hook" or not parts[-2].isdigit():
        return _reply(start_response, "404 Not Found", "not found")

    try:
        size = int(environ.get("CONTENT_LENGTH") or 0)
    except ValueError:
        size = 0
    if size <= 0 or size > 1024 * 1024:
        return _reply(start_response, "400 Bad Request", "bad size")
    try:
        data = json.loads(environ["wsgi.input"].read(size).decode("utf-8"))
    except Exception:
        return _reply(start_response, "400 Bad Request", "bad json")

    bot_id = int(parts[-2])
    path_secret = parts[-1]
    header_secret = environ.get("HTTP_X_TELEGRAM_BOT_API_SECRET_TOKEN", "")

    try:
        t = asyncio.run_coroutine_threadsafe(accept(bot_id, path_secret, header_secret), _loop).result(timeout=25)
    except Exception:
        log.exception("accept failed")
        return _reply(start_response, "500 Internal Server Error", "error")
    if t is None:
        return _reply(start_response, "403 Forbidden", "forbidden")

    asyncio.run_coroutine_threadsafe(dispatch(t, data), _loop)
    return _reply(start_response, "200 OK", "ok")
