"""The FR-01 gate: which turns the general lane answers.

One rule: the classifier decides HR vs non-HR. With general chat switched on,
every non-HR turn is answered by the general lane (ACTIVE_LLM_PROVIDER), for
any role. Switched off, it gets the HR redirect exactly as before. HR turns
never reach the gate.
"""
import inspect

import pytest

import services.hr_graph as hg


def _state(**kw):
    s = {"query": "explain the difference between revenue and profit",
         "intent": "non_hr", "is_hr": False,
         "company_id": "674", "conversation_id": "c1",
         "general_chat_enabled": True}
    s.update(kw)
    return s


# -- the switch --------------------------------------------------------------

def test_flag_on_routes_a_general_question_to_the_general_lane():
    assert hg._route_after_classify(_state()) == "general_chat_node"


def test_flag_off_routes_exactly_where_it_does_today():
    assert hg._route_after_classify(_state(general_chat_enabled=False)) == "non_hr_node"


def test_the_key_missing_entirely_is_off():
    """AC-06. A state built by anything that does not know about this feature
    must get today's behaviour. Off is the absence of a yes."""
    s = _state()
    del s["general_chat_enabled"]
    assert hg._route_after_classify(s) == "non_hr_node"


@pytest.mark.parametrize("value", [None, 0, "", "true", "false", 1, "yes"])
def test_only_the_boolean_True_turns_it_on(value):
    """`is not True`, not truthiness: the string "false" is truthy."""
    assert hg._route_after_classify(_state(general_chat_enabled=value)) == "non_hr_node"


# -- every non-HR turn, any role, any length ---------------------------------

@pytest.mark.parametrize("query", [
    "explain the difference between revenue and profit",
    "Write a follow-up email", "photosynthesis", "what is EBITDA",
    "tell me a joke", "make it shorter",
])
def test_every_non_hr_turn_is_answered(query):
    assert hg._route_after_classify(_state(query=query)) == "general_chat_node"


@pytest.mark.parametrize("role", [
    {"is_manager": False, "is_manager_jwt": False},
    {"is_manager": True, "is_manager_jwt": True},
    {"is_manager": None},
])
def test_no_role_is_excluded(role):
    assert hg._route_after_classify(_state(**role)) == "general_chat_node"


# -- HR turns are untouched --------------------------------------------------

@pytest.mark.parametrize("intent,expected", [
    ("policy", "policy_rag_node"),
    ("apply_leave", "leave_action_node"),
    ("leave_eligibility", "leave_eligibility_node"),
    ("clarify_needed", "clarify_node"),
    ("follow_up", "hr_response_node"),
    ("policy_draft", "policy_draft_node"),
])
def test_an_hr_intent_never_reaches_the_gate(intent, expected):
    """AC-02/AC-05: the flag being ON cannot change where an HR turn goes."""
    assert hg._route_after_classify(_state(intent=intent, is_hr=True)) == expected


@pytest.mark.parametrize("query,intent,expected", [
    ("explain why my attendance wasnt marked", "attendance_explain", "attendance_explain_node"),
    ("explain my leave balance", "leave_balance", "leave_action_node"),
    ("explain the leave policy", "policy", "policy_rag_node"),
    ("explain my shift timing", "shift_query", "shift_query_node"),
])
def test_an_hr_question_starting_with_explain_keeps_its_own_node(query, intent, expected):
    s = _state(query=query, intent=intent, is_hr=True)
    assert hg._route_after_classify(s) == expected


def test_the_gate_is_the_last_branch():
    """If the branch is ever moved above the HR routes, HR turns could be
    answered as general chat."""
    src = inspect.getsource(hg._route_after_classify)
    gate_at = src.index("_general_chat_may_take_the_turn")
    for hr_marker in ('intent == "policy"', "_LEAVE_ACTION_INTENTS",
                      "_ATTENDANCE_EXPLAIN_INTENTS", "_SHIFT_QUERY_INTENTS"):
        assert src.index(hr_marker) < gate_at, (
            f"{hr_marker} now routes AFTER the general-chat gate - the gate "
            "must stay the last branch")


def test_an_errored_turn_still_ends_rather_than_chatting():
    assert hg._route_after_classify(_state(error="boom")) == hg.END
