"""Context resolution utilities for agents."""

from __future__ import annotations

from typing import Any


def resolve_context(
    context: dict[str, Any],
    logger: Any = None,
) -> tuple[dict[str, Any], dict[str, Any], list[dict[str, Any]], list[Any]]:
    """Extract and merge prompt params, tools, and agents from context.

    Parses the Fluxibly context convention:

        prompt_params:
            "system": dict — params only for system prompt
            "user": dict — params only for user prompt
            Other keys — shared params applied to all prompts.
            Prompt-specific params override shared params.

        tools: list[dict] — additional tool definitions
        agents: list[BaseAgent] — additional agents for this call

    Returns:
        Tuple of (system_params, user_params, runtime_tools, runtime_agents)
    """
    prompt_params = context.get("prompt_params", {})

    # Separate shared params from prompt-specific params
    system_specific = prompt_params.get("system", {})
    user_specific = prompt_params.get("user", {})
    shared_params = {
        k: v for k, v in prompt_params.items() if k not in ("system", "user")
    }

    # Merge: shared + prompt-specific (specific overrides shared)
    system_params = {**shared_params, **system_specific}
    user_params = {**shared_params, **user_specific}

    runtime_tools: list[dict[str, Any]] = context.get("tools", [])
    runtime_agents: list[Any] = context.get("agents", [])

    if logger:
        agent_names = []
        for a in runtime_agents:
            if isinstance(a, dict):
                agent_names.append(a.get("name", "<bundle>"))
            else:
                agent_names.append(a.config.name)
        logger.info(
            "Resolved context: system_params={sp}, user_params={up}, "
            "runtime_tools={rt}, runtime_agents={ra}",
            sp=list(system_params.keys()),
            up=list(user_params.keys()),
            rt=len(runtime_tools),
            ra=agent_names,
        )

    return system_params, user_params, runtime_tools, runtime_agents
