"""Author: Vasiliy Zdanovskiy
email: vasilyvz@gmail.com

Optional WebSocket correlation envelope for transfer_session events (schema_version, job_id, ids).
"""

from __future__ import annotations

from typing import Any


def merge_transfer_correlation_envelope(
    transfer_id: str,
    payload: dict[str, Any] | None,
) -> dict[str, Any]:
    """
    Attach stable correlation fields from transfer session metadata when available.

    Never raises; on missing store/session returns a copy of the original payload.
    """
    tid = str(transfer_id).strip()
    base: dict[str, Any] = dict(payload) if payload else {}
    if tid == "":
        return base
    try:
        from mcp_proxy_adapter.api.handlers import get_transfer_store

        session = get_transfer_store().try_load_session_metadata(tid)
    except Exception:
        return base
    if session is None:
        return base
    out = dict(base)
    out.setdefault("schema_version", 1)
    if session.job_id:
        out["job_id"] = session.job_id
    if session.correlation_id:
        out["correlation_id"] = session.correlation_id
    if session.command:
        out["command"] = session.command
    if str(session.direction) == "upload":
        out["inbound_transfer_id"] = session.transfer_id
    else:
        out["outbound_transfer_id"] = session.transfer_id
    if session.inbound_transfer_id and str(session.direction) == "download":
        out["inbound_transfer_id"] = session.inbound_transfer_id
    return out
