"""Routing policy: templates / Ollama vs document RAG."""

from __future__ import annotations

from app.saas.chat_router import is_ollama_concept, needs_document_grounding, route_chat
from app.saas.finance_intent import classify_finance_intent


def test_smalltalk_never_uses_docs():
    for q in ("hi", "how are you", "thanks", "bye", "how's it going"):
        r = route_chat(q)
        assert not r.use_docs, q
        assert r.target.startswith("template_"), (q, r.target)


def test_math_is_calculator():
    r = route_chat("What is 12*8?")
    assert r.target == "calculator"
    assert not r.use_docs


def test_statement_field_and_credits_route_to_docs():
    for q in (
        "what is the state account branch number?",
        "what is the branch code?",
        "what is my IFSC?",
        "how many credits were made?",
        "how many credits were ,ade?",
    ):
        r = route_chat(q)
        assert r.use_docs, (q, r)
        assert r.target == "structured_or_rag", (q, r)
        assert classify_finance_intent(q) in {"statement_summary", "payment_count"}, q


def test_concepts_still_ollama():
    for q in (
        "What is EBITDA?",
        "Explain depreciation",
        "What is a balance sheet?",
        "Difference between GAAP and IFRS",
    ):
        assert is_ollama_concept(q), q
        r = route_chat(q)
        assert r.target == "ollama_concept", (q, r.target)
        assert not r.use_docs
        assert r.use_ollama


def test_personal_spend_uses_docs():
    for q in (
        "How much did I spend?",
        "How much spent on grocery?",
        "Paid to Blinkit",
        "Spend on 16 July",
        "Show my biggest expenses",
    ):
        r = route_chat(q)
        assert r.use_docs, (q, r)
        assert r.target == "structured_or_rag", (q, r.target)
        assert r.primary_intent == "document_lookup", (q, r)


def test_kb_metadata_not_content_summary():
    for q in (
        "Tell me about the knowledge base",
        "how many documents do I have?",
        "what is the filename?",
        "how many pages are indexed?",
    ):
        r = route_chat(q)
        assert r.primary_intent == "document_metadata", (q, r)
        assert r.target == "kb_metadata", (q, r)
        assert r.use_docs is True
        assert r.use_ollama is False


def test_five_primary_intents():
    from app.saas.intent_router import classify_primary_intent

    assert classify_primary_intent("hi").intent == "conversational"
    assert classify_primary_intent("What is 12*8?").intent == "calculation"
    assert classify_primary_intent("What is EBITDA?").intent == "general_knowledge"
    assert classify_primary_intent("how many documents do I have?").intent == "document_metadata"
    assert classify_primary_intent("How much did I spend?").intent == "document_lookup"
    assert classify_primary_intent("what if I cut spending by 20%?").intent == "calculation"


def test_typo_greeting_kello():
    from app.rag.chain import _detect_intent, _likely_greeting

    assert _likely_greeting("kello")
    assert _detect_intent("KELLO") == "greeting"
    r = route_chat("KELLO")
    assert r.target == "template_greeting"
    assert not r.use_docs


def test_typo_greeting_hi_bracket():
    from app.rag.chain import _detect_intent
    from app.saas.chat_router import route_chat

    assert _detect_intent("hi]") == "greeting"
    r = route_chat("hi]")
    assert r.target == "template_greeting"
    assert not r.use_docs


def test_payments_on_date_is_date_lookup():
    q = "did i make any payments on 1 august"
    assert classify_finance_intent(q) == "date_lookup"
    r = route_chat(q)
    assert r.use_docs
    assert r.finance_intent == "date_lookup"


def test_spend_after_date_is_not_follow_up():
    from app.saas.conversation import classify_conversational_intent

    assert classify_conversational_intent("How much did I spend?", has_history=True) == "new_question"
    assert classify_conversational_intent("How much spent on grocery?", has_history=True) == "new_question"
    assert classify_finance_intent("How much spent on grocery?") == "category_spending"


def test_compound_help_question_uses_docs_path_for_capability():
    q = "how can you help me, what do you know"
    r = route_chat(q)
    assert r.target == "template_help", r
    assert not r.use_docs


def test_statement_period_uses_docs_not_ollama():
    q = "What is the statement period?"
    r = route_chat(q)
    assert r.use_docs, r
    assert r.target == "structured_or_rag", r
    assert r.finance_intent == "statement_summary"


def test_vague_and_personal_never_use_docs():
    for q in (
        "complete?",
        "ok",
        "my name is toby",
        "what is my name?",
        "yo",
    ):
        r = route_chat(q)
        assert not r.use_docs, (q, r)
        assert r.target.startswith("template_"), (q, r.target)


def test_which_statement_uses_docs_inventory():
    from app.saas.knowledge_state import is_kb_meta_question

    q = "which statement?"
    assert is_kb_meta_question(q)
    r = route_chat(q)
    assert r.use_docs
    assert r.target == "kb_metadata"
    assert r.primary_intent == "document_metadata"
    assert r.finance_intent == "document_qa"


def test_help_analyse_routes_to_docs():
    r = route_chat("help me analyse the pdf")
    assert r.target == "structured_or_rag", r
    assert r.use_docs
    assert classify_finance_intent("help me analyse the pdf") == "statement_summary"


def test_name_from_statement_not_overview_dump():
    q = "this is my bank statement, what do you think my name is"
    assert classify_finance_intent(q) == "statement_summary"
    from app.saas.finance_intent import is_statement_identity_question

    assert is_statement_identity_question(q)
    r = route_chat(q)
    assert r.use_docs
    assert r.target == "structured_or_rag"


def test_bank_name_and_today_and_pdf_concept():
    from app.saas.chat_router import is_today_date_question, is_ollama_concept
    from app.saas.finance_intent import is_statement_field_question, is_profit_loss_question

    assert is_statement_field_question("what is my bank name?")
    assert route_chat("what is my bank name?").use_docs
    assert is_today_date_question("what is the date todat")
    assert route_chat("what is the date todat").target == "template_today"
    assert classify_finance_intent("what is a pdf") == "general"
    assert is_ollama_concept("what is a pdf")
    assert route_chat("what is a pdf").target == "ollama_concept"
    assert is_profit_loss_question("by looking at my bank statement do you think im in profit or loss")
    assert route_chat("by looking at my bank statement do you think im in profit or loss").use_docs


def test_casual_checkins_not_full_welcome():
    for q in ("yo", "wassup", "sup", "whats up"):
        r = route_chat(q)
        assert r.use_docs is False, (q, r)
        assert r.target == "template_how_are_you", (q, r)


def test_assistant_meta_skips_rag():
    for q in (
        "who are you?",
        "what can you do?",
        "tell me about the bot",
        "tell me about yourself",
    ):
        r = route_chat(q)
        assert r.use_docs is False, (q, r)
        assert r.target in {"template_help", "template_clarify", "ollama_concept"}, (q, r)
        assert r.target == "template_help", (q, r)


def test_self_intro_and_name_recall():
    from app.saas.chat_router import is_ask_my_name, is_ask_first_question, is_self_intro
    from app.saas.conversation import get_session_display_name, set_session_display_name
    from app.saas.intent_router import is_kb_tech_concept_question

    assert is_self_intro("my name is toby") == "Toby"
    assert is_self_intro("im harry") == "Harry"
    assert is_self_intro("i'm harry") == "Harry"
    assert route_chat("im harry").target == "template_personal"
    assert is_kb_tech_concept_question("what is indexing")
    assert not is_kb_tech_concept_question("what is a stock market index")
    assert is_ask_my_name("what is my name?")
    assert is_ask_first_question("what was my first question?")
    assert route_chat("what was my first question?").target == "template_personal"
    set_session_display_name("sess-name", "Toby")
    assert get_session_display_name("sess-name") == "Toby"


def test_suggest_followups_adapt_to_intent():
    from app.saas.assistant_policy import suggest_followups

    spend = suggest_followups(finance_intent="spending_summary", has_statement=True, has_docs=True)
    overview = suggest_followups(finance_intent="statement_summary", has_statement=True, has_docs=True)
    assert spend
    assert overview
    assert spend != overview or spend[0] != overview[0]
