import threading
from typing import Any, Optional

_abort = threading.Event()
_sb_ref: Optional[Any] = None
_lock = threading.Lock()


class AbortedError(RuntimeError):
    pass


def clear() -> None:
    _abort.clear()


def set_flag() -> None:
    _abort.set()


def is_aborted() -> bool:
    return _abort.is_set()


def check() -> None:
    if _abort.is_set():
        raise AbortedError("aborted")


def register_sb(sb: Any) -> None:
    global _sb_ref
    with _lock:
        _sb_ref = sb


def clear_sb() -> None:
    global _sb_ref
    with _lock:
        _sb_ref = None


def nuke_driver() -> None:
    with _lock:
        ref = _sb_ref
    if ref is None:
        return
    # SB context has .driver; nodriver Browser has .stop()
    try:
        driver = getattr(ref, "driver", None)
        if driver is not None:
            try:
                driver.quit()
                return
            except Exception:
                pass
    except Exception:
        pass
    try:
        stop = getattr(ref, "stop", None)
        if callable(stop):
            try:
                stop()
            except Exception:
                pass
    except Exception:
        pass
