import contextvars
import uuid
import logging

logger = logging.getLogger(__name__)

# 定义全局上下文变量
_trace_id_ctx = contextvars.ContextVar('trace_id', default=None)
_user_ctx = contextvars.ContextVar('user', default=None)

class TrackerContext:
    @staticmethod
    def start_trace(trace_id=None):
        if not trace_id:
            trace_id = uuid.uuid4().hex
        token = _trace_id_ctx.set(trace_id)
        return trace_id

    @staticmethod
    def get_trace_id():
        return _trace_id_ctx.get()

    @staticmethod
    def set_user(user):
        return _user_ctx.set(user)
    
    @staticmethod
    def get_user():
        return _user_ctx.get()

    @staticmethod
    def get_user_id():
        user = _user_ctx.get()
        if user and getattr(user, 'is_authenticated', False):
            return str(user.pk)
        return None

    @staticmethod
    def get_username():
        user = _user_ctx.get()
        if user and getattr(user, 'is_authenticated', False):
            return getattr(user, 'username', getattr(user, 'email', str(user.pk)))
        return None
