import sys
import traceback
from .client import send_async
from .payload import base_payload

def _handler(exc_type, exc, tb):
    """
    Global exception hook (best-effort).
    Triggered only for uncaught exceptions on main thread.
    """
    payload = base_payload()
    payload.update({
        "error_type": exc_type.__name__,
        "message": str(exc),
        "stack_trace": "".join(traceback.format_tb(tb))
    })
    send_async("/v1/sdk/exception", payload)

def register_exception_hook():
    sys.excepthook = _handler

def capture_exception(exc):
    """
    Explicit exception capture (RELIABLE).
    Must be used inside try/except blocks.
    """
    payload = base_payload()
    payload.update({
        "error_type": type(exc).__name__,
        "message": str(exc),
        "stack_trace": traceback.format_exc()
    })
    send_async("/v1/sdk/exception", payload)
