from __future__ import annotations

from typing import Any

from amsdal_utils.config.manager import AmsdalConfigManager


def resolve_reference_resource(class_name: str) -> str | None:
    try:
        return AmsdalConfigManager().get_connection_name_by_model_name(class_name)
    except Exception:
        return None


def build_reference_payload(
    class_name: str,
    object_id: Any,
    *,
    resource: str | None = None,
) -> dict[str, object]:
    resolved_resource = resource if resource is not None else resolve_reference_resource(class_name)
    payload: dict[str, object] = {
        'class_name': class_name,
        'object_id': str(object_id),
    }

    if resolved_resource is not None:
        payload['resource'] = resolved_resource

    return {'$ref': payload}
