from typing import Any

from ..contexts import InputMessage, MessagePart


def extract_system_message_from_kwargs(
    kwargs: dict[str, Any],
    system_key: str = "system",
    config_key: str | None = "config",
) -> InputMessage | None:
    """Extract system message from kwargs and return as InputMessage.

    Handles both direct system parameter (Anthropic) and config.system_instruction
    (Google) patterns.

    Args:
        kwargs: The kwargs dict to extract from
        system_key: The key to check for system message (default: "system")
        config_key: The key to check for config object (default: "config")

    Returns:
        InputMessage with system role and text content, or None if no system message found
    """
    system_content = kwargs.get(system_key)
    if system_content:
        return InputMessage(
            role="system",
            parts=[MessagePart(type="text", content=str(system_content))]
        )

    if config_key:
        config = kwargs.get(config_key)
        if config:
            system_instruction = None
            if isinstance(config, dict):
                system_instruction = config.get("system_instruction")
            elif hasattr(config, "system_instruction"):
                system_instruction = getattr(config, "system_instruction", None)

            if system_instruction:
                return InputMessage(
                    role="system",
                    parts=[MessagePart(type="text", content=str(system_instruction))]
                )

    return None
