from __future__ import annotations
import weakref
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from instaui.facade_ui.webview_launcher import WebViewLauncher


class WebViewContext:
    def __init__(self):
        self._launcher_ref: weakref.ReferenceType[WebViewLauncher] | None = None

    @property
    def launcher(self) -> WebViewLauncher:
        if self._launcher_ref is None:
            raise ValueError("Launcher has not been set")
        launcher = self._launcher_ref()
        assert launcher is not None
        return launcher

    def _set_launcher(self, launcher: WebViewLauncher):
        if self._launcher_ref is not None:
            raise ValueError("Launcher has already been set")

        def on_launcher_destroyed(_):
            self._launcher_ref = None

        self._launcher_ref = weakref.ref(launcher, on_launcher_destroyed)


_context: WebViewContext | None = None


def get_context() -> WebViewContext:
    global _context
    if _context is None:
        _context = WebViewContext()
    return _context
