"""Only the caller can be the applicant (28 Oct): a pet, a thing, a relative,
a friend or a named person wanting leave / regularization gets the model's
"only you can apply for yourself" reply. A person or pet named only as the
REASON for the caller's own leave does not."""
import pytest

import services.ai_service as ai_service
import services.classify_node as classify_node
import services.hr_graph as hg
from services import leave_slot_service, slot_store
from services.attendance import _seed_pending_regularization
from services.nlp_service import resolve_applicant

COMPANY_ID = 4290

OTHER = [
    # subject not in any list, other grammar
    "my cat want to apply leave or regularization", "my dog apply leave", "cat wants leave",
    "tiger wants to apply leave", "my goldfish needs a sick leave", "my parrot is applying for leave",
    "my cats want leave", "\U0001F436 wants to apply leave", "i think my cat wants to apply leave",
    # things
    "my laptop wants a leave", "my car needs leave", "my phone wants to regularize attendance",
    "my plant needs a day off",
    # the target after for / on behalf of
    "apply leave for my cat tomorrow", "apply leave on behalf of my cat", "regularize attendance for my dog",
    "book comp off for my bike", "actually this leave is for my dog", "apply it for my cat",
    # people
    "he wants to apply leave", "my team member wants to apply leave", "can my brother apply leave for tomorrow",
    "my dog wants to apply leave",
    # Hinglish
    "meri billi ko chutti chahiye", "mere kutte ko leave apply karni hai", "mere dost ki leave apply kar do",
    "mere dost ko leave chahiye", "tota leave lena chahta hai",
    # object pronouns and "for <someone>" with no leave word (28 Oct)
    "apply for him", "apply for her", "apply leave for him", "apply leave for her",
    "apply regularization for her", "apply sick leave for them", "book leave for him tomorrow",
    "can you apply leave for him", "apply for my wife", "apply for someone", "apply leave for her tomorrow",
    "apply leave on behalf of him", "uske liye leave apply karo", "unke liye chutti", "unki leave apply kar do",
    # other actions
    "cancel my cat's leave", "check my dog's leave balance", "regularize my brother's attendance",
    "show my cat's attendance",
]

SELF = [
    "my cat is sick, I need leave", "leave to take my dog to the vet", "apply leave for my sister's wedding",
    "apply leave for my mother", "my phone broke, need half day", "my phone broke need half day",
    "my manager wants me to apply leave", "can you apply leave for me", "apply leave for tomorrow",
    "mere bhai ki shaadi ke liye leave chahiye", "my car broke down, regularize today", "I want to apply leave",
    "i need a sick leave tomorrow", "what is my leave balance", "show my attendance",
    "apply casual leave for 3rd nov", "regularize 7 oct", "can I apply leave for diwali",
    "my dog is sick, I need leave", "i need leave for my dog's surgery", "apply leave because my cat is unwell",
    "leave for my mother's surgery", "please apply leave for me for tomorrow", "tomorrow I want leave",
    "mujhe kal chutti chahiye", "my manager asked me to apply regularization",
    "apply leave for my brother's engagement", "I want to take leave for my car service",
    "mera kutta bimar hai, mujhe chutti chahiye", "the cat ate my homework, need leave",
    "my colleague is on leave so I need to cover",
    # "for <thing to apply for>", a reason after "her", a date in Hinglish
    "apply for leave", "apply for a job", "apply for a loan", "how to apply for a passport",
    "apply leave for her wedding", "apply leave for his birthday party", "apply for me",
    "us din ke liye leave chahiye", "is hafte ke liye leave", "apply for work from home tomorrow",
    "apply leave for home shifting", "apply leave for my team",
    # team views stay the permission gate's
    "my team's leave", "show my team's attendance", "show my team member's attendance",
    "approve rahul's leave", "show rahul's attendance",
]


@pytest.mark.parametrize("q", OTHER)
def test_someone_else_is_the_applicant(q):
    assert resolve_applicant(q) == "other"


@pytest.mark.parametrize("q", SELF)
def test_the_caller_is_the_applicant(q):
    assert resolve_applicant(q) in ("self", None)


@pytest.mark.parametrize("q", ["Bruno wants to apply leave", "Rahul wants to apply leave",
                               "can Priya apply leave from my login"])
def test_a_name_is_left_to_the_ai_check(q):
    assert resolve_applicant(q) == "unclear"


def test_no_hr_action_is_none():
    assert resolve_applicant("my cat is cute") is None


# ── the classifier, in every flow state ─────────────────────────────────────

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


@pytest.fixture
def conv(request):
    c = f"applicant-{request.node.name}"[:80]
    yield c
    leave_slot_service.clear_slots(COMPANY_ID, c)
    slot_store.clear_slots("regularization", COMPANY_ID, c)


async def _classify(q, conv):
    return await classify_node.classify_node(
        {"query": q, "company_id": COMPANY_ID, "conversation_id": conv, "bearer_token": "t",
         "usage_events": [], "is_manager": False, "last_intent": None, "context": [],
         "date_typo_checked": True}, _Writer())


def _no_draft(conv):
    pass


def _apply_draft(conv):
    leave_slot_service.set_slots(COMPANY_ID, conv, {"leave_type": "casual_leave",
                                                    "from_date": "2026-10-29", "to_date": "2026-10-29"})


def _confirmation_card(conv):
    leave_slot_service.set_slots(COMPANY_ID, conv, {"leave_type": "casual_leave", "from_date": "2026-10-29",
                                                    "to_date": "2026-10-29", "step": "awaiting_confirmation"})


def _reg_offer(conv):
    _seed_pending_regularization(COMPANY_ID, conv, date_iso="2026-10-07", offer_only=True)


def _reg_draft(conv):
    slot_store.set_slots("regularization", COMPANY_ID, conv, {"entries": [{"date": "2026-10-07"}]})


@pytest.mark.parametrize("setup", [_no_draft, _apply_draft, _confirmation_card, _reg_offer, _reg_draft])
@pytest.mark.parametrize("q", ["my cat want to apply leave or regularization", "apply it for my cat",
                               "apply for him", "apply leave for her"])
async def test_every_flow_state(conv, setup, q):
    setup(conv)
    out = await _classify(q, conv)
    assert out["intent"] == classify_node.APPLY_FOR_SOMEONE_ELSE_INTENT
    assert out["turn_instruction"] == classify_node.APPLY_FOR_SOMEONE_ELSE_INSTRUCTION


# ── the AI check, for names only ────────────────────────────────────────────

def _ai_says(monkeypatch, result):
    calls = []

    async def _check(q):
        calls.append(q)
        if isinstance(result, Exception):
            raise result
        return result
    monkeypatch.setattr(ai_service, "classify_applicant", _check)
    return calls


@pytest.mark.parametrize("who", ["another_person", "animal", "object"])
async def test_a_confident_other_verdict_refuses(monkeypatch, conv, who):
    _ai_says(monkeypatch, (who, 0.9, None))
    out = await _classify("Bruno wants to apply leave", conv)
    assert out["intent"] == classify_node.APPLY_FOR_SOMEONE_ELSE_INTENT


@pytest.mark.parametrize("verdict", [("self", 0.9, None), ("another_person", 0.4, None), (None, 0.0, None)])
async def test_self_low_confidence_or_failure_lets_it_through(monkeypatch, conv, verdict):
    _ai_says(monkeypatch, verdict)

    async def _label(prompt, labels, fallback_label="unknown"):
        return "apply_leave", None, False
    monkeypatch.setattr(classify_node, "classify_intent_structured", _label)
    out = await _classify("Bruno wants to apply leave", conv)
    assert out["intent"] != classify_node.APPLY_FOR_SOMEONE_ELSE_INTENT


async def test_the_ai_check_is_not_called_when_the_rules_decide(monkeypatch, conv):
    calls = _ai_says(monkeypatch, ("another_person", 0.9, None))
    await _classify("my cat wants to apply leave", conv)
    assert calls == []


async def test_classify_applicant_fails_open(monkeypatch):
    async def _boom(*a, **k):
        raise RuntimeError("down")
    monkeypatch.setattr(ai_service, "_call_llm", _boom)
    assert await ai_service.classify_applicant("Bruno wants leave") == (None, 0.0, None)


async def test_classify_applicant_parses(monkeypatch):
    async def _ok(*a, **k):
        return {"choices": [{"message": {"content": '{"applicant": "animal", "confidence": 0.8}'}}]}
    monkeypatch.setattr(ai_service, "_call_llm", _ok)
    assert (await ai_service.classify_applicant("Bruno wants leave"))[:2] == ("animal", 0.8)


# ── the main classifier's label gets the same reply ─────────────────────────

def test_the_label_is_valid():
    assert classify_node.APPLY_FOR_SOMEONE_ELSE_INTENT in classify_node._VALID_INTENT_LABELS


async def test_the_llm_label_alone_gets_the_instruction(monkeypatch):
    seen = []

    async def _stream(messages, max_tokens=None, use_tools=True):
        seen.append(messages[1]["content"])
        yield {"type": "chunk", "content": "Only you can apply for your own leave."}
    monkeypatch.setattr(hg, "_call_llm_stream", _stream)
    out = await hg.hr_response_node({"query": "my hamster deserves a holiday off work",
                                     "intent": classify_node.APPLY_FOR_SOMEONE_ELSE_INTENT,
                                     "context": [], "usage_events": []}, _Writer())
    assert out["response_text"] == "Only you can apply for your own leave."
    assert seen[0].startswith(classify_node.APPLY_FOR_SOMEONE_ELSE_INSTRUCTION)
