import logging
from soagila.core.tcmg.memory_models import MemoryQueryResult

logger = logging.getLogger("soagila.llm.prompt")


# =============================================
# SYSTEM PROMPT TEMPLATES
# =============================================

SYSTEM_PROMPTS = {
    "banking": """You are an AI assistant at Anatolian Digital Bank, powered by SOAGILA cognitive memory. You primarily help with banking, but you can also answer general questions naturally. Do NOT force every topic back to banking — if the customer asks about something else, answer it helpfully. Use memory context to personalize. Be concise and professional. Respond in the customer's language.""",

    "healthcare": """You are an intelligent healthcare assistant AI powered by SOAGILA — the Sovereign Agent Intelligence Layer.

You have access to the patient's cognitive memory profile. Use past interaction history to provide personalized care guidance.

IMPORTANT: You are NOT a doctor. Always recommend consulting healthcare professionals for medical decisions.
Use memory context to track patient history and preferences naturally.""",

    "general": """You are an intelligent AI assistant powered by SOAGILA — the Sovereign Agent Intelligence Layer.

You have access to a cognitive memory system that tracks your interactions. Use the provided memory context to give personalized, context-aware responses.

Reference past conversations naturally when relevant. Handle conflicting information gracefully if noted.""",
}


def get_system_prompt(scenario: str = "banking") -> str:
    """Get the system prompt for a given scenario."""
    return SYSTEM_PROMPTS.get(scenario, SYSTEM_PROMPTS["general"])


# =============================================
# PROMPT BUILDER
# =============================================

def build_prompt(
    user_message: str,
    memory_context: MemoryQueryResult | None = None,
    session_history: list[dict] | None = None,
    scenario: str = "banking",
) -> tuple[str, str]:
    """
    Build a complete prompt with memory context.
    Returns (system_prompt, user_prompt).
    """
    system_prompt = get_system_prompt(scenario)

    # Build context sections
    context_parts = []

    if memory_context:
        # Working Memory Context
        if memory_context.working:
            wm_items = []
            for m in memory_context.working[:3]:
                wm_items.append(f"  - {m.content[:100]}")
            if wm_items:
                context_parts.append(
                    "=== CURRENT CONTEXT ===\n" +
                    "\n".join(wm_items)
                )

        # Episodic Memory Context
        if memory_context.episodic:
            em_items = []
            for m in memory_context.episodic[:3]:
                em_items.append(f"  - {m.content[:100]}")
            if em_items:
                context_parts.append(
                    "=== PAST INTERACTIONS ===\n" +
                    "\n".join(em_items)
                )

        # Semantic Memory Context
        if memory_context.semantic:
            sm_items = []
            for m in memory_context.semantic[:3]:
                desc = m.pattern_description or m.content
                sm_items.append(f"  - {desc[:100]}")
            if sm_items:
                context_parts.append(
                    "=== KNOWN PATTERNS ===\n" +
                    "\n".join(sm_items)
                )

        # Arbitration Note
        if memory_context.arbitration:
            arb = memory_context.arbitration
            if isinstance(arb, dict) and arb.get("conflicts_detected", 0) > 0:
                explanation = arb.get("explanation", "")
                if explanation:
                    context_parts.append(
                        f"=== ARBITRATION NOTE ===\n"
                        f"Memory conflict detected and resolved: {explanation}"
                    )

    # Session History
    if session_history:
        history_items = []
        for msg in session_history[-4:]:  # Last 4 messages
            role = msg.get("role", "user")
            content = msg.get("content", "")[:150]
            history_items.append(f"  {role.upper()}: {content}")
        if history_items:
            context_parts.append(
                "=== RECENT CONVERSATION ===\n" +
                "\n".join(history_items)
            )

    # Assemble user prompt
    if context_parts:
        context_block = "\n\n".join(context_parts)
        user_prompt = f"""{context_block}

=== CURRENT MESSAGE ===
{user_message}

Please respond to the current message, using the memory context above to provide a personalized, context-aware response."""
    else:
        user_prompt = user_message

    return system_prompt, user_prompt


def format_memories_for_display(memory_context: MemoryQueryResult) -> dict:
    """Format memory context for dashboard display."""
    return {
        "working_count": len(memory_context.working),
        "episodic_count": len(memory_context.episodic),
        "semantic_count": len(memory_context.semantic),
        "has_arbitration": memory_context.arbitration is not None,
        "primed": memory_context.primed,
        "working_topics": list(set(
            tag for m in memory_context.working for tag in m.topic_tags
        ))[:5],
        "episodic_topics": list(set(
            tag for m in memory_context.episodic for tag in m.topic_tags
        ))[:5],
    }
