from __future__ import annotations

import uuid
from typing import Mapping


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


def _header_value(headers: Mapping[str, str], *names: str) -> str:
    for name in names:
        value = headers.get(name)
        if value:
            return str(value).strip()
    return ""


def resolve_trace_id(headers: Mapping[str, str]) -> str:
    trace_id = _header_value(headers, "x-trace-id", "X-Trace-Id", "x-request-id", "X-Request-Id")
    return trace_id or next_trace_id()


def resolve_request_id(headers: Mapping[str, str], *, fallback_trace_id: str) -> str:
    request_id = _header_value(headers, "x-request-id", "X-Request-Id")
    return request_id or fallback_trace_id
