"""UAT full run (26 Oct 2026, qateam@gmail.com): UV-01, UV-02, UV-03, UV-05, UV-06."""
import json
from datetime import date

import pytest

import services.classify_node as classify_node
import services.hr_graph as hg
from services import leave_slot_service, slot_store
from services.chat_service import _parse_ai_response, history_text



class _Writer(list):
    def __call__(self, e):
        self.append(e)

    def answer(self):
        return [e for e in self if e.get("type") == "done"][-1]["data"]["answer"]


# ── UV-01: "Is it a holiday in our company?" six turns after "Diwali kya hai?" ──

CAL = {"http_status": 200, "body": {"success": True, "data": {"holidays": [
    {"holiday_name": "Diwali", "holiday_date": "2026-11-08"},
    {"holiday_name": "Christmas", "holiday_date": "2026-12-25"}]}}}

LT06 = [
    ("Diwali kya hai?", "Diwali is the festival of lights..."),
    ("Ye kyun manaya jata hai?", "It celebrates the return of Lord Rama..."),
    ("Is din kya kya karte hain?", "People clean homes, light diyas..."),
    ("Why do people light diyas on it?", "Diyas symbolise light over darkness..."),
    ("Iska Lakshmi Puja se kya connection hai?", "Lakshmi Puja is performed on the main day..."),
    ("When is it in 2026?", "In 2026 it falls on Sunday, 8 November."),
]


def _ctx(pairs):
    out = []
    for q, a in pairs:
        out += [{"role": "user", "content": q}, {"role": "assistant", "content": a}]
    return out


@pytest.fixture
def calendar(monkeypatch):
    async def _get(*a, **k):
        return CAL
    monkeypatch.setattr(hg.erp_client, "get_leave_holidays", _get)
    monkeypatch.setattr(hg, "_today_in_app_timezone", lambda: date(2026, 10, 26))


async def test_holiday_named_turns_back_is_found(calendar):
    w = _Writer()
    await hg.hr_response_node({"query": "Is it a holiday in our company?", "intent": "policy",
                               "context": _ctx(LT06), "usage_events": []}, w)
    assert w.answer() == "Yes - Diwali - Sun, 08 Nov 2026 is on your holiday calendar."


async def test_nothing_named_asks_which_not_contradicts(calendar):
    w = _Writer()
    await hg.hr_response_node({"query": "Is it a holiday in our company?", "intent": "policy",
                               "context": [], "usage_events": []}, w)
    assert w.answer().startswith("Which holiday do you mean?")
    assert "can't see that" not in w.answer()


def test_a_holiday_list_answer_names_no_single_holiday():
    ctx = _ctx([("show holidays", "Your upcoming holidays:\n- Diwali - ...\n- Christmas - ...")])
    assert hg._holiday_named_in(CAL["body"]["data"]["holidays"], "is it a holiday?", ctx) is None


# ── UV-02: card data reaches history; follow-ups about it are not "no info" ──

BALANCE = {"answer": "Here's your current leave balance.",
           "leave_quota": [{"leave_type": "Casual Leave", "total": 100, "used": 2, "remaining": 98}],
           "options": ["Apply leave"]}


def test_history_keeps_the_card_data():
    text = history_text(BALANCE)
    assert text.startswith("Here's your current leave balance.")
    assert '"remaining": 98' in text and "Apply leave" not in text


def test_db_fallback_history_keeps_it_too():
    raw = json.dumps({"success": True, "intent": "leave_balance", "data": BALANCE})
    assert '"remaining": 98' in _parse_ai_response(raw)


def test_a_plain_answer_is_unchanged():
    assert history_text({"answer": "Paris."}) == "Paris."


def test_a_long_card_is_capped():
    big = {"answer": "x", "leaves": [{"reason": "r" * 100}] * 100}
    assert len(history_text(big)) < 1700


@pytest.mark.parametrize("query", ["Interesting, why is that?", "Why is it showing Not Recorded?",
                                   "How do I fix it?", "Which one is the oldest?"])
def test_follow_up_about_the_card(query):
    ctx = [{"role": "user", "content": "What is my leave balance?"},
           {"role": "assistant", "content": history_text(BALANCE)}]
    assert hg._asks_about_the_card_shown(query, ctx)


def test_not_after_a_plain_answer():
    ctx = [{"role": "user", "content": "q"}, {"role": "assistant", "content": "Paris."}]
    assert not hg._asks_about_the_card_shown("why is that?", ctx)


async def test_the_no_info_template_is_not_sent(monkeypatch):
    async def _stream(messages, max_tokens=None, use_tools=True):
        yield {"type": "chunk", "content": "You have 98 Casual Leave days left because..."}
    monkeypatch.setattr(hg, "_call_llm_stream", _stream)
    ctx = [{"role": "user", "content": "What is my leave balance?"},
           {"role": "assistant", "content": history_text(BALANCE)}]
    w = _Writer()
    await hg.hr_response_node({"query": "Interesting, why is that?", "intent": "policy",
                               "policy_lookup_failed": True, "policy_context": None,
                               "context": ctx, "usage_events": []}, w)
    assert w.answer() != hg.NO_INFO_FALLBACK


# ── UV-02 (HR-06): "Which one is the oldest?" after an EMPTY team list ──

EMPTY_TEAM = [{"role": "user", "content": "Show my team's pending leave requests"},
              {"role": "assistant",
               "content": "Great news! There are currently no pending leave requests for your team."}]


@pytest.mark.parametrize("query", ["Which one is the oldest?", "which is the latest one",
                                   "Who applied first?", "which ones?"])
def test_which_of_an_empty_team_list(query):
    assert classify_node._asks_which_of_the_list_shown(query, EMPTY_TEAM, "HRMS_TEAM_LEAVE_QUERY")


@pytest.mark.parametrize("query", ["what is the capital of france", "which is the oldest civilisation in the world and why",
                                   "show my oldest leave"])
def test_not_an_unrelated_question(query):
    assert not classify_node._asks_which_of_the_list_shown(query, EMPTY_TEAM, "HRMS_TEAM_LEAVE_QUERY")


def test_not_after_a_general_answer():
    ctx = [{"role": "user", "content": "list famous paintings"},
           {"role": "assistant", "content": "Mona Lisa, The Starry Night..."}]
    assert not classify_node._asks_which_of_the_list_shown("Which one is the oldest?", ctx, "non_hr")


async def test_the_empty_list_follow_up_goes_to_the_hr_advisor():
    out = await classify_node.classify_node(
        {"query": "Which one is the oldest?", "company_id": COMPANY_ID, "conversation_id": "uv02-empty",
         "bearer_token": "t", "usage_events": [], "is_manager": True,
         "last_intent": "HRMS_TEAM_LEAVE_QUERY", "context": EMPTY_TEAM}, lambda e: None)
    assert out["intent"] == "follow_up"
    assert hg._route_after_classify(out) == "hr_response_node"


# ── UV-10 (HA-931): people-management advice is not a team card ──

@pytest.mark.parametrize("query", [
    "How should I give negative feedback to a team member?",
    "how do I handle an employee who is always absent",
    "tips to motivate my team",
    "what's the best way to talk to an underperforming colleague",
    "how should I approach a one-on-one with my reportee",
])
def test_people_advice_goes_to_the_advisor(query):
    assert classify_node._is_people_advice_question(query.lower())


@pytest.mark.parametrize("query", [
    "show my team members", "how do I see my team members", "how to handle leave encashment",
    "list my team", "how many leaves do I have",
])
def test_not_people_advice(query):
    assert not classify_node._is_people_advice_question(query.lower())


async def test_the_feedback_question_is_answered_as_advice():
    out = await classify_node.classify_node(
        {"query": "How should I give negative feedback to a team member?", "company_id": COMPANY_ID,
         "conversation_id": "uv10", "bearer_token": "t", "usage_events": [], "is_manager": True,
         "last_intent": None, "context": []}, lambda e: None)
    assert out["intent"] == "performance"
    assert hg._route_after_classify(out) not in ("team_members_node", "team_leave_query_node",
                                                 "team_attendance_node")


# ── UV-05: "Explain my balance in Hindi" ──

@pytest.mark.parametrize("query", ["Explain my balance in Hindi", "isko hindi me samjhao",
                                   "tell me this in tamil"])
def test_the_card_in_another_language(query):
    ctx = [{"role": "assistant", "content": history_text(BALANCE)}]
    assert classify_node._asks_for_the_card_in_another_language(query, ctx)


@pytest.mark.parametrize("query", ["Explain my balance in Hindi"])
def test_not_without_a_card(query):
    assert not classify_node._asks_for_the_card_in_another_language(
        query, [{"role": "assistant", "content": "Paris."}])


def test_not_a_translation_of_a_phrase():
    ctx = [{"role": "assistant", "content": history_text(BALANCE)}]
    assert not classify_node._asks_for_the_card_in_another_language("what is my leave balance", ctx)


# ── UV-06: the summary is plain text ──

def test_summary_instruction_forbids_markdown():
    assert "no bold (**)" in hg.CHAT_SUMMARY_INSTRUCTION


# ── UV-03: the carry-on/discard question is asked once per draft ──

COMPANY_ID = 4243


@pytest.fixture
def draft(request, monkeypatch):
    conv = f"uv03-{request.node.name}"
    leave_slot_service.set_slots(COMPANY_ID, conv, {"leave_type": "sick_leave",
                                                    "from_date": "2026-10-26"})
    for ns in (classify_node._HELD_QUESTION_NAMESPACE, classify_node._DRAFT_REMINDED_NAMESPACE):
        slot_store.clear_slots(ns, COMPANY_ID, conv)

    async def _no_shift(q):
        return None, 0.0, None

    async def _classify(prompt, labels, fallback_label="unknown"):
        return "attendance", None, False
    monkeypatch.setattr(classify_node.ai_service, "classify_shift_intent", _no_shift)
    monkeypatch.setattr(classify_node, "classify_intent_structured", _classify)
    yield conv
    leave_slot_service.clear_slots(COMPANY_ID, conv)
    for ns in (classify_node._HELD_QUESTION_NAMESPACE, classify_node._DRAFT_REMINDED_NAMESPACE):
        slot_store.clear_slots(ns, COMPANY_ID, conv)


async def _turn(query, conv, last_intent="apply_leave"):
    return await classify_node.classify_node(
        {"query": query, "company_id": COMPANY_ID, "conversation_id": conv, "bearer_token": "t",
         "usage_events": [], "is_manager": False, "last_intent": last_intent}, lambda e: None)


async def test_asked_once_then_answered(draft):
    first = await _turn("show my last 1 month attendance", draft)
    assert first["intent"] == "clarify_needed"

    second = await _turn("show my attendance for this week", draft, last_intent="clarify_needed")
    assert second["intent"] == "attendance"
    assert leave_slot_service.get_slots(COMPANY_ID, draft)["leave_type"] == "sick_leave"


async def test_a_new_draft_is_asked_about_again(draft):
    await _turn("show my last 1 month attendance", draft)
    leave_slot_service.set_slots(COMPANY_ID, draft, {"leave_type": "casual_leave",
                                                     "from_date": "2026-11-02"})
    out = await _turn("show my attendance for this week", draft)
    assert out["intent"] == "clarify_needed"


# ── UV-04: a one-word guess asks before opening a team member's record ──

import services.individual_report as individual_report  # noqa: E402
from tests.test_individual_report import (  # noqa: E402,F401 -- fixtures
    FakeWriter as _IRWriter, base_state, mock_extraction, name_match_response,
    patch_leave_api, _fake_report_store,
)

PHIL = {"employee_id": 77, "employee_name": "Phil salt", "employee_number": "E77"}


def _guessed(query):
    s = base_state(query)
    s["report_subject_was_guessed"] = True
    return s


async def test_one_guessed_word_asks_first(monkeypatch):
    mock_extraction(monkeypatch, employee_name="salt")
    calls = patch_leave_api(monkeypatch, name_match_response([PHIL]))
    w = _IRWriter()

    out = await individual_report.individual_report_node(_guessed("salt"), w)

    done = w.of_type("done")[-1]
    assert done["intent"] == individual_report.GUESSED_NAME_CHECK_INTENT
    assert out["response_text"] == ('Did you mean **Phil salt** from your team, or would you '
                                    'like to know what "salt" means? Or is it something else?')
    assert done["data"]["options"] == ["Search Phil salt's employee details",
                                      "General details about salt", "Something else"]
    assert len(calls) == 1, "no record fetched for Phil salt"
    assert not w.of_type("fetching_individual_report")


async def test_a_full_name_still_opens_the_record(monkeypatch):
    mock_extraction(monkeypatch, employee_name="Phil salt")
    calls = patch_leave_api(monkeypatch, name_match_response([PHIL]),
                            {"http_status": 200, "body": {"success": True,
                                                          "data": {"leaves": []}}})
    w = _IRWriter()

    await individual_report.individual_report_node(_guessed("Phil salt"), w)

    assert w.of_type("done")[-1]["intent"] != individual_report.GUESSED_NAME_CHECK_INTENT
    assert calls[-1]["employee_id"] == 77


async def test_a_prompted_one_word_answer_is_not_questioned(monkeypatch):
    """A reply to "which team member?" is an answer, not a guess."""
    mock_extraction(monkeypatch, employee_name="salt")
    calls = patch_leave_api(monkeypatch, name_match_response([PHIL]),
                            {"http_status": 200, "body": {"success": True,
                                                          "data": {"leaves": []}}})
    w = _IRWriter()

    await individual_report.individual_report_node(base_state("salt"), w)

    assert calls[-1]["employee_id"] == 77


async def _choice(query, last_intent=individual_report.GUESSED_NAME_CHECK_INTENT):
    return await classify_node.classify_node(
        {"query": query, "company_id": COMPANY_ID, "conversation_id": "uv04",
         "bearer_token": "t", "usage_events": [], "is_manager": True,
         "last_intent": last_intent}, lambda e: None)


async def test_employee_details_runs_the_lookup_for_that_person():
    out = await _choice("Search Phil salt's employee details")
    assert out["intent"] == "manager_leave_request_lookup"
    assert out["query"] == "Phil salt"
    assert out["report_subject_was_guessed"] is False
    import services.hr_graph as _hg
    assert _hg._route_after_classify(out) != "non_hr_node"


async def test_general_details_is_a_general_answer():
    out = await _choice("General details about salt")
    assert out["intent"] == "non_hr"
    assert out["query"] == "Tell me about salt."


async def test_something_else_asks_what_they_want():
    out = await _choice("Something else")
    assert out["intent"] == "clarify_needed"
    assert out["clarify_message"] == "Sure - what would you like to know?"


def test_the_buttons_are_read_back():
    assert individual_report.guessed_name_choice("search phil salt's employee details") == (
        "employee", "phil salt")
    assert individual_report.guessed_name_choice("General details about salt") == (
        "general", "salt")
    assert individual_report.guessed_name_choice("salt") is None


# ── "leave balance in hindi / german / japanese": the card, explained in it ──

from services.nlp_service import requested_reply_language  # noqa: E402


@pytest.mark.parametrize("query, lang", [
    ("leave balance in hindi", "hindi"), ("explain leave balance in japanese", "japanese"),
    ("leave balance in German", "german"), ("mera leave balance hindi me batao", "hindi"),
    ("balance in english", None), ("what is my leave balance", None),
])
def test_requested_reply_language(query, lang):
    assert requested_reply_language(query) == lang


@pytest.mark.parametrize("query", ["leave balance in hindi", "explain leave balance in japanese",
                                   "leave balance in german", "mera leave balance hindi me batao"])
async def test_a_balance_asked_in_a_language_fetches_the_card(query):
    out = await classify_node.classify_node(
        {"query": query, "company_id": COMPANY_ID, "conversation_id": "lang-new",
         "bearer_token": "t", "usage_events": [], "is_manager": False,
         "last_intent": None, "context": []}, lambda e: None)
    assert out["intent"] == "leave_balance"


CARD_DONE = {"type": "done", "intent": "leave_balance", "is_hr": True,
             "data": {"answer": "Here's your current leave balance.",
                      "leave_quota": {"casual_leave": {"total": 20, "used": 5, "remaining": 15}}},
             "message": "Here's your current leave balance.", "usage_events": []}


@pytest.fixture
def balance_card(monkeypatch):
    seen = {}

    async def _impl(state, writer):
        writer({"type": "leave_balance", "data": CARD_DONE["data"]})
        writer(CARD_DONE)
        return {"response_text": CARD_DONE["message"], "usage_events": []}

    async def _advisor(state, writer):
        seen["advisor"] = state
        writer({"type": "chunk", "content": "आपके पास 15 दिन बचे हैं।"})
        writer({"type": "done", "data": {"answer": "आपके पास 15 दिन बचे हैं।"}})
        return {"response_text": "आपके पास 15 दिन बचे हैं।", "usage_events": []}

    monkeypatch.setattr(hg, "leave_action_node_impl", _impl)
    monkeypatch.setattr(hg, "hr_response_node", _advisor)
    return seen


async def test_the_card_is_kept_and_explained_in_the_language(balance_card):
    w = _Writer()
    await hg.leave_action_node({"query": "leave balance in hindi", "intent": "leave_balance",
                                "context": [], "usage_events": []}, w)
    done = [e for e in w if e.get("type") == "done"]
    assert len(done) == 1, "one done event: the card's, with the explanation"
    assert done[0]["data"]["leave_quota"] == CARD_DONE["data"]["leave_quota"]
    assert done[0]["data"]["answer"] == "आपके पास 15 दिन बचे हैं।"
    assert any(e.get("type") == "leave_balance" for e in w)
    assert balance_card["advisor"]["query"] == "Explain this leave balance in Hindi."
    assert '"remaining": 15' in balance_card["advisor"]["context"][-1]["content"]


async def test_without_a_language_it_is_the_card_as_before(balance_card):
    w = _Writer()
    await hg.leave_action_node({"query": "leave balance", "intent": "leave_balance",
                                "context": [], "usage_events": []}, w)
    assert w.answer() == "Here's your current leave balance."
    assert "advisor" not in balance_card
