from contextvars import ContextVar
from typing import Optional
from .sessions import set_step as _set_step

_ctx: ContextVar[dict] = ContextVar("_ussd_ctx", default={})

class _USSDProxy:
    @property
    def msisdn(self) -> Optional[str]:
        return _ctx.get().get("msisdn")

    @property
    def session(self) -> Optional[str]:
        return _ctx.get().get("session")

    @property
    def input(self) -> Optional[str]:
        return _ctx.get().get("input")

    def screen(self, name: str):
        sid = self.session
        if not sid:
            raise RuntimeError("No active session to set screen on.")
        _set_step(sid, name)

ussd = _USSDProxy()

def _set_context(msisdn: str, session: str, user_input: str):
    _ctx.set({"msisdn": msisdn, "session": session, "input": user_input})

def _clear_context():
    _ctx.set({})
