from contextvars import ContextVar
from typing import Optional, List, Tuple
from .sessions import set_step as _set_step

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

class _USSDProxy:
    def __init__(self):
        self._response_text = None
        self._should_end = False

    @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 menu(self, title: str, options: List[Tuple[str, str]]) -> str:
        """Display a menu with numbered options.

        Args:
            title: Menu title
            options: List of (label, route) tuples
        """
        lines = [title]
        for idx, (label, route) in enumerate(options, 1):
            lines.append(f"{idx}. {label}")

        self._response_text = "\n".join(lines)

        # Store menu options for navigation in the session
        ctx = _ctx.get()
        menu_map = {str(idx): route for idx, (_, route) in enumerate(options, 1)}
        ctx["menu_map"] = menu_map
        ctx["is_menu"] = True
        _ctx.set(ctx)

        return self._response_text

    def screen(self, text: str) -> str:
        """Display a text screen.

        Args:
            text: Text to display
        """
        self._response_text = text
        return text

    def next(self, route: str):
        """Set the next route to navigate to.

        Args:
            route: Route path to navigate to on next input
        """
        sid = self.session
        if not sid:
            raise RuntimeError("No active session to set next route on.")
        _set_step(sid, route)

    def end(self):
        """End the USSD session."""
        sid = self.session
        if not sid:
            raise RuntimeError("No active session to end.")
        _set_step(sid, "end")
        self._should_end = True

    def get_response(self) -> Optional[str]:
        """Get the response text."""
        return self._response_text

    def should_end_session(self) -> bool:
        """Check if session should end."""
        return self._should_end

    def reset(self):
        """Reset the proxy state."""
        self._response_text = None
        self._should_end = False

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({})
