"""Assistant policy helpers — conversation vs document memory, follow-ups, voice."""

from __future__ import annotations

from typing import Any

from app.models.schemas import StructuredInsight

# Compact policy injected into RAG / Ollama system prompts.
ANALYST_POLICY = """
You are an AI assistant that answers from the user's uploaded knowledge base. Be accurate, never hallucinate, and sound like a helpful colleague.

## Step 0 — Classify the question (do this mentally before answering)
A) Knowledge-base question — about uploaded files (facts, figures, names, dates, summaries, “this PDF/document”).
B) Conversational / meta / general knowledge — greetings, who you are, or topics not tied to the uploads.
C) Unclear — ask one short clarifying question.

Only Category A may use Evidence notes. Categories B and C must ignore document notes even if they appear in the prompt.

## Two independent memories
1) Conversation memory — names and prior turns the user told you.
2) Document memory — facts from uploaded files only.

Never confuse them. If both could apply, clarify briefly.

## Answer shape
- Lead with a direct answer, then brief supporting detail from the notes.
- Prefer document facts over assumptions. If information is missing, say so — never invent numbers, names, or dates.
- Attribute naturally (“Based on your uploaded document…” / “From your knowledge base…”).
- Follow-ups must use Recent conversation.
- Never mention RAG, chunks, vectors, embeddings, extraction, or incomplete indexing.

## Tone
Natural, concise, conversational. No greetings on every turn. No goodbyes. No filler.
""".strip()


def suggest_followups(
    *,
    finance_intent: str | None = None,
    insight: StructuredInsight | None = None,
    has_statement: bool = False,
    has_docs: bool = False,
) -> list[str]:
    """Adaptive next questions — vary by intent; avoid identical chips every turn."""
    intent = (insight.intent if insight else None) or finance_intent or "general"

    if not has_docs and not has_statement:
        return [
            "Upload a document to Knowledge",
            "What can you help me with?",
            "What is depreciation?",
        ]

    by_intent: dict[str, list[str]] = {
        "statement_summary": [
            "How much did I spend in total?",
            "Show my biggest expenses",
            "How much money did I receive?",
            "List all payments",
            "Whose statement is this?",
        ],
        "spending_summary": [
            "Show my biggest expenses",
            "How much spent on groceries?",
            "Which merchant got the most?",
            "Spend by date",
            "How much did I receive?",
        ],
        "category_spending": [
            "How much did I spend overall?",
            "Show my biggest expenses",
            "List all payments",
            "Spend on a specific date",
        ],
        "merchant_analysis": [
            "How much did I spend overall?",
            "Show my biggest expenses",
            "List payments to this merchant again",
            "How much spent on groceries?",
        ],
        "date_lookup": [
            "How much did I spend overall?",
            "Show spend by date",
            "List all payments",
            "How much did I receive?",
        ],
        "income": [
            "How much did I spend?",
            "What is my net cashflow?",
            "List all payments",
            "Show the statement overview",
        ],
        "payment_count": [
            "How much did I spend?",
            "List all payments",
            "Show my biggest expenses",
            "How much did I receive?",
        ],
        "transaction_search": [
            "How much did I spend?",
            "Show my biggest expenses",
            "How much spent on groceries?",
            "Spend on a specific date",
        ],
        "document_qa": [
            "How much did I spend?",
            "Whose statement is this?",
            "What is the statement period?",
            "Show my biggest expenses",
        ],
        "insights": [
            "How much did I spend?",
            "Show my biggest expenses",
            "How much did I receive?",
            "List all payments",
        ],
        "period_coverage": [
            "How much did I spend?",
            "Show spend by date",
            "List all payments",
        ],
    }

    picks = list(by_intent.get(intent, []))
    if has_statement and not picks:
        picks = [
            "How much did I spend?",
            "Show my biggest expenses",
            "How much did I receive?",
            "List all payments",
        ]
    if not picks:
        picks = [
            "Summarize the document",
            "What is this file about?",
            "Tell me about the knowledge base",
            "What should I ask you?",
        ] if (has_docs or has_statement) else [
            "Tell me about the knowledge base",
            "What should I ask you?",
            "Explain depreciation",
        ]

    # Prefer 4 varied chips — avoid defaulting every turn to “summarize”
    return picks[:4]


def format_suggestions_footer(suggestions: list[str]) -> str:
    if not suggestions:
        return ""
    lines = ["", "You might also ask:"]
    for s in suggestions[:4]:
        lines.append(f"• {s}")
    return "\n".join(lines)
