"""System prompts for the companion."""

from __future__ import annotations

from typing import Any

from companion.rag.search import SearchResult


def build_system_prompt(
    persona: dict[str, Any],
    retrieved_context: list[SearchResult] | None = None,
    memory_context: str | None = None,
) -> str:
    """Build the system prompt for the companion.

    Args:
        persona: Companion persona configuration (name, role, tone, style, boundaries)
        retrieved_context: Optional RAG context from vault search
        memory_context: Optional memory summary from session

    Returns:
        The complete system prompt
    """
    name = persona.get("name", "Companion")
    role = persona.get("role", "companion")
    tone = persona.get("tone", "reflective")
    style = persona.get("style", "questioning")
    boundaries = persona.get("boundaries", [])

    # Base persona description
    base_prompt = f"""You are {name}, a {tone}, {style} {role}.

Your role is to be a thoughtful, reflective companion—not to impersonate or speak for the user, but to explore alongside them. You know their life through their journal entries and are here to help them reflect, remember, and explore patterns.

Core principles:
- You do not speak as the user. You speak to them.
- You listen deeply and reflect patterns back gently.
- You ask questions that help them explore their own thoughts.
- You respect the boundaries of a confidante, not an oracle.
"""

    # Add boundaries section
    if boundaries:
        base_prompt += "\nBoundaries:\n"
        for boundary in boundaries:
            base_prompt += f"- {boundary.replace('_', ' ').title()}\n"

    # Add retrieved context section if available
    context_section = ""
    if retrieved_context:
        context_section += "\n\nRelevant context from your vault:\n"
        for i, ctx in enumerate(retrieved_context[:8], 1):  # Limit to top 8 chunks
            text = ctx.text.strip()
            if text:
                context_section += f"[{i}] From {ctx.citation}:\n{text}\n\n"

    # Add memory context if available
    memory_section = ""
    if memory_context:
        memory_section = f"\n\nContext from your conversation:\n{memory_context}"

    # Final instructions
    closing = """

When responding:
- Draw from the vault context if relevant, but don't force it
- Be concise but thoughtful—no unnecessary length
- If uncertain, acknowledge the uncertainty
- Ask follow-up questions that deepen reflection
"""

    return base_prompt + context_section + memory_section + closing


def format_conversation_history(
    messages: list[dict[str, Any]], max_turns: int = 10
) -> str:
    """Format conversation history for prompt context.

    Args:
        messages: List of message dicts with 'role' and 'content'
        max_turns: Maximum number of recent turns to include

    Returns:
        Formatted conversation history
    """
    if not messages:
        return ""

    # Take only recent messages
    recent = messages[-max_turns * 2 :] if len(messages) > max_turns * 2 else messages

    formatted = []
    for msg in recent:
        role = msg.get("role", "user")
        content = msg.get("content", "")
        if content.strip():
            formatted.append(f"{role.upper()}: {content}")

    return "\n\n".join(formatted)
