from __future__ import annotations

from typing import Any, Dict, Optional

from oasyce.services.runtime_identity import (
    normalize_runtime_actor,
    resolve_agent_id,
    resolve_runtime_actor_trace,
    resolve_session_id,
)


def resolve_coordination_context(
    *,
    default_agent_id: str,
    session_id: Optional[str] = None,
    source: str = "",
) -> Dict[str, Any]:
    runtime_actor = resolve_runtime_actor_trace(
        default_agent_id=default_agent_id,
        session_id=session_id,
        source=source,
    )
    return {
        **runtime_actor,
        "agent_id": str(
            runtime_actor.get("agent_id") or resolve_agent_id(default_agent_id)
        ).strip(),
        "session_id": str(
            runtime_actor.get("session_id") or resolve_session_id(session_id)
        ).strip(),
        "source": str(runtime_actor.get("source") or source or default_agent_id).strip(),
    }


def with_actor_metadata(
    metadata: Optional[Dict[str, Any]],
    *,
    actor_key: str,
    actor: Dict[str, Any],
) -> Dict[str, Any]:
    payload = dict(metadata or {})
    payload[actor_key] = dict(actor)
    return payload


def normalize_coordination_trace(coordination: Any) -> Dict[str, Any]:
    if not isinstance(coordination, dict):
        return {}
    payload: Dict[str, Any] = {}
    for actor_key in ("discovered_by", "recommended_by", "resolved_by", "executed_by"):
        actor = normalize_runtime_actor(coordination.get(actor_key))
        if actor:
            payload[actor_key] = actor
    return payload
