"""
tenant.py - per-bot context for the multi-bot (webhook) mode.

Every incoming update runs inside its own asyncio task. webapp.py sets the values below for that
task, so the old single-bot code in Main.py (global `bot`, `ADMIN_ID`, 'Cuibcc.db') automatically
talks to the right reseller bot, admin and database file.
When nothing is set (running Main.py alone with polling) everything behaves exactly as before.
"""
import contextvars
import os

_bot = contextvars.ContextVar("tenant_bot", default=None)
_admin = contextvars.ContextVar("tenant_admin", default=None)
_db = contextvars.ContextVar("tenant_db", default=None)
_uname = contextvars.ContextVar("tenant_username", default=None)

_default_bot = None
DEFAULT_ADMIN = int(os.environ.get("ADMIN_ID", "0") or 0)
DEFAULT_DB = "Cuibcc.db"


def set_default_bot(b):
    """Standalone (polling) mode: the one real Bot object."""
    global _default_bot
    _default_bot = b


def use(bot, admin_id, db_path, username):
    """Call at the start of the task that handles one update."""
    _bot.set(bot)
    _admin.set(int(admin_id))
    _db.set(db_path)
    _uname.set(username or "")


def admin_id() -> int:
    v = _admin.get()
    return DEFAULT_ADMIN if v is None else v


def db_path() -> str:
    return _db.get() or DEFAULT_DB


def redirect_url(default_username: str = "") -> str:
    u = (_uname.get() or default_username or "").lstrip("@")
    return "https://t.me/" + u


class BotProxy:
    """Stands in for the old global `bot`; forwards to the bot of the current update."""

    def __getattr__(self, name):
        b = _bot.get() or _default_bot
        if b is None:
            raise RuntimeError("No bot is active in this context.")
        return getattr(b, name)
