"""Prompt processing utilities for agents."""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from fluxibly.agent.base import AgentConfig


def process_prompt(prompt: str, params: dict[str, Any]) -> str:
    """Replace {param} placeholders in prompt with param values."""
    processed = prompt
    for key, value in params.items():
        processed = processed.replace(f"{{{key}}}", str(value))
    return processed


def prepare_system_prompt(
    messages: list[dict[str, Any]],
    system_prompt: str | None,
    params: dict[str, Any],
) -> list[dict[str, Any]]:
    """Process system prompt template and inject into messages.

    If system_prompt is provided, replaces any existing system message
    from the caller.
    """
    if not system_prompt:
        return list(messages)

    processed = process_prompt(system_prompt, params)
    working: list[dict[str, Any]] = [{"role": "system", "content": processed}]

    for msg in messages:
        if msg["role"] != "system":
            working.append(msg)

    return working


def prepare_user_prompt(
    messages: list[dict[str, Any]],
    user_prompt: str | None,
    params: dict[str, Any],
) -> list[dict[str, Any]]:
    """Apply user prompt template to the last user message.

    Replaces {input} in the template with the original user content.
    """
    if not user_prompt:
        return messages

    for i in range(len(messages) - 1, -1, -1):
        if messages[i]["role"] == "user":
            original_input = messages[i]["content"]
            processed = process_prompt(user_prompt, params)
            processed = processed.replace("{input}", str(original_input))
            messages[i] = {**messages[i], "content": processed}
            break

    return messages


def prepare_prompts(
    messages: list[dict[str, Any]],
    config: AgentConfig,
    system_params: dict[str, Any],
    user_params: dict[str, Any],
    logger: Any = None,
) -> list[dict[str, Any]]:
    """Prepare working messages by applying system and user prompt templates."""
    working = prepare_system_prompt(
        messages, config.system_prompt, system_params
    )
    working = prepare_user_prompt(working, config.user_prompt, user_params)

    if logger:
        logger.info("Prepared prompts: {n} messages", n=len(working))
        logger.debug("Messages:\n{msgs}", msgs=working)

    return working
