"""Analyst intent + retrieval/reasoning separation."""

from app.saas.analyst_intent import (
    classify_analyst_intent,
    is_financial_analysis_question,
    is_factual_document_lookup,
)
from app.saas.finance_intent import classify_finance_intent, is_financial_advice_question
from app.saas.kb import infer_chunk_kind
from app.saas.reason import scrub_internal_user_text


def test_financial_analysis_intent():
    for q in (
        "How can I save money?",
        "How can I reduce spending?",
        "Am I spending too much?",
        "Where should I cut expenses?",
        "Analyze my habits",
    ):
        assert is_financial_analysis_question(q), q
        assert is_financial_advice_question(q), q
        r = classify_analyst_intent(q)
        assert r.intent == "financial_analysis", (q, r)
        assert r.needs_document and r.needs_llm
        assert "merchant" in r.chunk_kinds or "transaction" in r.chunk_kinds


def test_factual_lookup_uses_header_kinds():
    for q in (
        "What is the statement period?",
        "Whose statement is this?",
        "What year is the statement?",
    ):
        assert is_factual_document_lookup(q), q
        r = classify_analyst_intent(q)
        assert r.intent == "document_lookup", (q, r)
        assert "header" in r.chunk_kinds or "statement_period" in r.chunk_kinds


def test_general_knowledge_no_docs():
    r = classify_analyst_intent("What is an LLM?")
    assert r.intent == "general_knowledge"
    assert r.needs_document is False


def test_general_chat():
    r = classify_analyst_intent("who are you")
    assert r.intent == "general_chat"


def test_mixed_spend_total():
    r = classify_analyst_intent("How much did I spend?")
    assert r.intent == "mixed"
    assert r.needs_document and r.needs_llm


def test_finance_intent_advice():
    assert classify_finance_intent("how can I save money") == "financial_advice"


def test_infer_chunk_kind():
    assert infer_chunk_kind("Account holder: John Doe IFSC: ABCD") == "header"
    assert infer_chunk_kind("Total money paid: 12000 Payments made: 40") == "totals"
    assert infer_chunk_kind("Paid to Zepto on 16 Jul ₹450") in {"transaction", "merchant"}
    assert infer_chunk_kind("Statement period: 03 Jul 26 - 02 Aug 26") == "statement_period"


def test_howto_not_statement_rag():
    from app.saas.analyst_intent import classify_analyst_intent
    from app.saas.chat_router import route_chat
    from app.saas.finance_intent import classify_finance_intent
    from app.saas.intent_router import classify_primary_intent, is_general_knowledge_question

    for q in (
        "how to plant a tree",
        "how to bake bread",
        "how do I tie a tie",
        "what is photosynthesis",
    ):
        assert is_general_knowledge_question(q), q
        assert classify_finance_intent(q) == "general", (q, classify_finance_intent(q))
        assert classify_primary_intent(q).intent == "general_knowledge", q
        assert classify_analyst_intent(q).intent == "general_knowledge", q
        assert route_chat(q).use_docs is False, q
        assert route_chat(q).target == "ollama_concept", q


def test_real_merchant_still_routes_to_docs():
    from app.saas.chat_router import route_chat
    from app.saas.finance_intent import classify_finance_intent

    q = "how much did I pay to Amazon"
    assert classify_finance_intent(q) == "merchant_analysis"
    assert route_chat(q).use_docs is True


def test_zomato_savings_advice_extracts_merchant():
    from app.saas.analyst_intent import classify_analyst_intent
    from app.saas.finance_intent import extract_merchant_query
    from app.saas.insight import analysis_evidence_dict, build_financial_analysis
    from app.models.schemas import InsightMetric, StructuredInsight

    q = "how can i save spending this much on zomato"
    assert extract_merchant_query(q) == "zomato"
    assert classify_analyst_intent(q).intent == "financial_analysis"

    job = {
        "filename": "demo.pdf",
        "metrics": {"money_out": 10000, "payments_made": 20, "money_in": 1000},
        "period_label": "1 Apr - 2 Aug",
        "rows": [
            {"date": "09 Apr", "description": "Paid to ZOMATO", "debit": 174.51, "credit": 0},
            {"date": "18 Jun", "description": "Paid to Zomato Ltd", "debit": 309.03, "credit": 0},
            {"date": "10 Apr", "description": "Transferred to Self", "debit": 5000, "credit": 0},
        ],
        "text": "Paid to ZOMATO 174.51\nPaid to Zomato Ltd 309.03\nTransferred to Self 5000",
    }
    insight = build_financial_analysis(job, q)
    assert insight.intent == "financial_advice"
    assert any("zomato" in (m.label or "").lower() for m in insight.metrics)
    evidence = analysis_evidence_dict(insight, q)
    assert evidence.get("focus_merchant", {}).get("name", "").lower() == "zomato"
    assert evidence["focus_merchant"].get("found") is True


def test_name_from_knowledge_base_is_identity_not_inventory():
    from app.saas.chat_router import route_chat
    from app.saas.finance_intent import is_statement_identity_question
    from app.saas.intent_router import classify_primary_intent, is_ask_my_name, is_document_metadata_question
    from app.saas.knowledge_state import is_kb_meta_question

    q = "based on the knowledge base what is my name"
    assert is_statement_identity_question(q)
    assert not is_kb_meta_question(q)
    assert not is_document_metadata_question(q)
    assert classify_primary_intent(q).intent == "document_lookup"
    assert route_chat(q).target == "structured_or_rag"
    assert route_chat(q).use_docs is True

    soft = "what do you think is my name"
    assert is_ask_my_name(soft)
    assert route_chat(soft).target == "template_personal"


def test_assistant_gender_and_vague_pings():
    from app.saas.chat_router import route_chat
    from app.saas.personality import is_identity_question

    for q in (
        "hi are you a boy or girl",
        "are you a boy or girl",
        "are you male or female",
        "who are you",
    ):
        assert is_identity_question(q), q
        assert route_chat(q).target == "template_help", q

    for q in ("what", "?", "huh"):
        r = route_chat(q)
        assert r.target == "template_clarify", (q, r)
        assert r.use_docs is False

