import uuid


def new_trace_id() -> str:
    return uuid.uuid4().hex


def ensure_trace_id(value: str = "", payload: dict | None = None) -> str:
    explicit = str(value or "").strip()
    if explicit:
        return explicit
    candidate = str((payload or {}).get("trace_id") or "").strip()
    if candidate:
        return candidate
    return new_trace_id()
