"""Data payloads and thread-local proxies for handler context (TgMsg, TgCmd, TgCb, TgArgs)."""
from __future__ import annotations

import threading
from typing import Any

from TgrEzLi.types import TgArgsData, TgCbData, TgCmdData, TgMsgData

# Thread-local storage for current handler payload
_local: threading.local = threading.local()


def _get_proxy(attr: str, label: str) -> Any:
    obj = getattr(_local, attr, None)
    if obj is None:
        raise AttributeError(f"{label} is not available in this context (use inside a handler).")
    return obj


class TgMsgProxy:
    """Proxy to current message payload; use only inside onMessage handlers."""

    def __getattr__(self, name: str) -> Any:
        return getattr(_get_proxy("TgMsg", "TgMsg"), name)


class TgCmdProxy:
    """Proxy to current command payload; use only inside onCommand handlers."""

    def __getattr__(self, name: str) -> Any:
        return getattr(_get_proxy("TgCmd", "TgCmd"), name)


class TgCbProxy:
    """Proxy to current callback payload; use only inside onCallback handlers."""

    def __getattr__(self, name: str) -> Any:
        return getattr(_get_proxy("TgCb", "TgCb"), name)


class TgArgsProxy:
    """Proxy to current API request body; use only inside onApiReq handlers."""

    def __getattr__(self, name: str) -> Any:
        return getattr(_get_proxy("TgArgs", "TgArgs"), name)


def set_context(TgMsg: TgMsgData | None = None, TgCmd: TgCmdData | None = None,
                TgCb: TgCbData | None = None, TgArgs: TgArgsData | None = None) -> None:
    """Set thread-local context (used by handlers module)."""
    _local.TgMsg = TgMsg
    _local.TgCmd = TgCmd
    _local.TgCb = TgCb
    _local.TgArgs = TgArgs


def clear_context() -> None:
    """Clear thread-local context."""
    _local.TgMsg = None
    _local.TgCmd = None
    _local.TgCb = None
    _local.TgArgs = None


# Public proxies (singletons)
TgMsg = TgMsgProxy()
TgCmd = TgCmdProxy()
TgCb = TgCbProxy()
TgArgs = TgArgsProxy()

__all__ = [
    "TgMsgData",
    "TgCmdData",
    "TgCbData",
    "TgArgsData",
    "TgMsg",
    "TgCmd",
    "TgCb",
    "TgArgs",
    "set_context",
    "clear_context",
]
