"""Coding is on the blacklist (HA-951): HelixAI answers general questions,
but does not write, fix, review or convert code.

Before this, a coding request was labelled non_hr and non_hr_node wrote the
code - "Write me a Python script to scrape a website" got a working scraper
(HA-951 sheet, Q-16). Talking ABOUT programming is still a general question
and is answered (Q-05, Q-16 turn 1).

The detector replaced patterns that called "give me the dress code policy",
"write a code of conduct" and "develop a training program for new hires"
coding requests. Those only misrouted before; now that a match REFUSES, a
false positive would refuse an HR question, so both lists below matter.
"""

from unittest.mock import AsyncMock, MagicMock, patch

import pytest

import services.classify_node as classify_node_mod
import services.hr_graph as hr_graph
from services.ai_service import GENERAL_CHAT_SYSTEM_PROMPT, GENERAL_CHAT_WEB_SEARCH_PROMPT, HR_SYSTEM_PROMPT
from services.nlp_service import fast_classify, is_code_request


CODE_REQUESTS = [
    "write python code to reverse a string",
    "Write me a Python script to scrape a website",
    "how to code a login page",
    "give me a javascript function for sorting",
    "write a sql query to get all employees",
    "fix this code: def f(x) return x",
    "debug my java program",
    "reverse a linked list in java",
    "write a for loop",
    "write code for a calculator",
    "create a react component for a login form",
    "can you give me the code",
    "convert this to python",
    "write a regex for email",
    "implement binary search in python",
    "write me a bash script to back up files",
    "generate html for a landing page",
    "need a python script that reads excel",
    "SELECT name FROM employees WHERE id=1 fix it",
    "write unit tests for my function",
    "show me sample code for an API call",
]

NOT_CODE_REQUESTS = [
    # HR wording the old patterns caught.
    "give me the dress code policy",
    "what is the dress code",
    "develop a training program for new hires",
    "create an onboarding program",
    "build a wellness program for employees",
    "write a code of conduct",
    "generate employee code for new joiner",
    "what is my employee code",
    "give me the pin code of our office",
    "create a job description for a python developer",
    "write a JD for a java developer",
    "write a leave application",
    "write an email to my manager",
    "create a policy for remote work",
    "make a training plan",
    "write a performance review for my team member",
    "give me a function-wise breakdown of the org",
    "write a query to HR about my salary",
    "convert my leave to work from home",
    "write my leave reason in hindi",
    "show me the html version of the policy",
    "apply leave for tomorrow",
    # Talking about programming is a general question.
    "What is Python?",
    "is python hard to learn?",
    "Where should I start?",
    "explain recursion",
    "what is an API",
    "what is the difference between java and python",
    "how do I learn python",
    "who made python",
    "what is sql",
]


@pytest.mark.parametrize("query", CODE_REQUESTS)
def test_code_requests_are_detected(query):
    assert is_code_request(query)


@pytest.mark.parametrize("query", NOT_CODE_REQUESTS)
def test_everything_else_is_not(query):
    assert not is_code_request(query)


@pytest.mark.parametrize("query", [
    "give me the dress code policy",
    "develop a training program for new hires",
    "write a code of conduct",
    "generate employee code for new joiner",
])
def test_hr_wording_is_no_longer_labelled_non_hr(query):
    intent, is_hr, _ = fast_classify(query)
    assert intent != "non_hr" and is_hr


class FakeWriter:
    def __init__(self):
        self.events = []

    def __call__(self, event):
        self.events.append(event)


def _state(query, context=None):
    return {"query": query, "context": context or [], "last_intent": None,
            "bearer_token": "t", "company_id": "3735",
            "conversation_id": "conv-1", "usage_events": []}


def _patched(label="non_hr"):
    return patch.multiple(classify_node_mod,
                          classify_intent_structured=AsyncMock(return_value=(label, None, False)),
                          _check_moderation=AsyncMock(return_value={"flagged": False}),
                          leave_slot_service=MagicMock(get_slots=MagicMock(return_value=None)))


@pytest.mark.parametrize("query", [
    "Write me a Python script to scrape a website",
    "write a sql query to get all employees",
])
async def test_classify_node_blocks_code_requests(query):
    writer = FakeWriter()
    with _patched():
        result = await hr_graph.classify_node(_state(query), writer)

    assert result["error"] == "flagged"
    assert hr_graph._route_after_classify(result) == hr_graph.END
    guardrail = [e for e in writer.events if e.get("type") == "guardrail"]
    assert guardrail and guardrail[0]["categories"] == ["coding"]
    assert guardrail[0]["message"] == classify_node_mod.CODING_BLOCKED_MESSAGE
    assert "hr" not in guardrail[0]["message"].lower().split()


async def test_code_request_mid_conversation_is_blocked_too():
    """Q-16: the request arrives as a follow-up to "What is Python?"."""
    context = [{"role": "user", "content": "What is Python?"},
               {"role": "assistant", "content": "Python is a high-level programming language."}]
    with _patched():
        result = await hr_graph.classify_node(
            _state("Write me a Python script to scrape a website", context), FakeWriter())

    assert result["error"] == "flagged"


async def test_a_question_about_programming_is_answered():
    with _patched():
        result = await hr_graph.classify_node(_state("What is Python?"), FakeWriter())

    assert not result.get("error")
    assert hr_graph._route_after_classify(result) == "non_hr_node"


@pytest.mark.parametrize("prompt", [GENERAL_CHAT_SYSTEM_PROMPT, GENERAL_CHAT_WEB_SEARCH_PROMPT, HR_SYSTEM_PROMPT])
def test_every_answer_prompt_refuses_code_as_a_backstop(prompt):
    assert "never write, complete, fix, review or convert code" in prompt
    assert classify_node_mod.CODING_BLOCKED_MESSAGE in prompt
