"""
Tests for services.ai_service.classify_intent_structured — the unified,
structured-output intent classifier that replaced the old blind-trust
fast_classify short-circuit (main.py's Fast-path 1) and the separate,
OpenAI-only check_hr_relevance gate.

Two layers, deliberately different in what they can prove:

1. Contract/plumbing tests (this file, CI-safe, mocked HTTP, fast,
   deterministic): prove classify_intent_structured always returns a label
   from the given enum no matter what the provider sends back — valid JSON,
   an off-list label, malformed JSON, or an outright HTTP failure — and that
   each provider's request is shaped correctly (JSON mode, temperature=0,
   correct model, max_completion_tokens not max_tokens for OpenAI). This
   catches regressions in the WIRING (e.g. the enum list drifting out of
   sync with the prompt, or a broken fallback path).

2. Full-dataset wiring test: for every (query, expected_intent) pair in
   tests/fixtures/intent_eval_dataset.py (180 cases spanning all 24 valid
   labels), build the REAL prompt via classify_node._build_intent_prompt, mock
   only the underlying HTTP call to return the expected label, and confirm
   it round-trips correctly. This proves prompt-building never crashes on
   any of the 180 real/authored queries and that the validation step never
   falsely rejects a legitimate enum value — it does NOT prove the LLM
   itself would classify these correctly, since that requires a real model
   call (slow, non-deterministic, costs tokens, needs live API keys) — see
   tests/multi_prompt_report.py for the periodic, manually-run live-accuracy
   sweep against a real provider, which is where that question is actually
   answered.
"""

import json
import pytest
from unittest.mock import MagicMock, patch

import services.ai_service as ai_service
from services.classify_node import _build_intent_prompt, _VALID_INTENT_LABELS
from tests.fixtures.intent_eval_dataset import INTENT_EVAL_DATASET


def _openai_response(content: str, usage=None) -> dict:
    return {
        "choices": [{"message": {"content": content}}],
        "usage": usage or {"prompt_tokens": 50, "completion_tokens": 5, "total_tokens": 55},
    }


def _mock_http_response(body: dict, status_code: int = 200):
    resp = MagicMock()
    resp.status_code = status_code
    resp.json.return_value = body
    if status_code >= 400:
        resp.raise_for_status.side_effect = Exception(f"HTTP {status_code}")
    else:
        resp.raise_for_status.return_value = None
    return resp


class TestClassifyIntentStructuredContract:

    async def test_valid_label_is_returned_as_is(self, monkeypatch):
        monkeypatch.setattr(ai_service, "ACTIVE_LLM_PROVIDER", "deepseek")
        resp = _mock_http_response(_openai_response(json.dumps({"intent": "leave_balance"})))
        with patch.object(ai_service, "_http") as mock_http:
            mock_http.post = MagicMock(return_value=_await(resp))
            label, usage, failed = await ai_service.classify_intent_structured(
                "some prompt", frozenset({"leave_balance", "apply_leave"}),
            )
        assert label == "leave_balance"
        assert usage is not None
        assert failed is False

    async def test_off_enum_label_falls_back(self, monkeypatch):
        """The exact failure mode structured output is meant to prevent —
        confirm the fallback actually engages if a provider ever returns
        something outside the given enum despite JSON mode."""
        monkeypatch.setattr(ai_service, "ACTIVE_LLM_PROVIDER", "deepseek")
        resp = _mock_http_response(_openai_response(json.dumps({"intent": "leave_request"})))
        with patch.object(ai_service, "_http") as mock_http:
            mock_http.post = MagicMock(return_value=_await(resp))
            label, usage, failed = await ai_service.classify_intent_structured(
                "some prompt", frozenset({"leave_balance", "apply_leave"}), fallback_label="general_hr",
            )
        assert label == "general_hr"
        assert failed is True

    async def test_malformed_json_falls_back(self, monkeypatch):
        monkeypatch.setattr(ai_service, "ACTIVE_LLM_PROVIDER", "deepseek")
        resp = _mock_http_response(_openai_response("not valid json{{{"))
        with patch.object(ai_service, "_http") as mock_http:
            mock_http.post = MagicMock(return_value=_await(resp))
            label, usage, failed = await ai_service.classify_intent_structured(
                "some prompt", frozenset({"leave_balance"}), fallback_label="general_hr",
            )
        assert label == "general_hr"
        assert failed is True

    async def test_http_failure_falls_back_and_does_not_raise(self, monkeypatch):
        monkeypatch.setattr(ai_service, "ACTIVE_LLM_PROVIDER", "deepseek")
        with patch.object(ai_service, "_http") as mock_http:
            mock_http.post = MagicMock(side_effect=Exception("connection refused"))
            label, usage, failed = await ai_service.classify_intent_structured(
                "some prompt", frozenset({"leave_balance"}), fallback_label="general_hr",
            )
        assert label == "general_hr"
        assert failed is True
        assert usage is None

    async def test_deepseek_request_is_deterministic_json_mode(self, monkeypatch):
        monkeypatch.setattr(ai_service, "ACTIVE_LLM_PROVIDER", "deepseek")
        resp = _mock_http_response(_openai_response(json.dumps({"intent": "leave_balance"})))
        captured = {}

        async def _fake_post(url, json=None, headers=None, **kwargs):
            captured["url"] = url
            captured["json"] = json
            return resp

        with patch.object(ai_service, "_http") as mock_http:
            mock_http.post = _fake_post
            await ai_service.classify_intent_structured("prompt text", frozenset({"leave_balance"}))

        assert captured["url"] == ai_service.DEEPSEEK_URL
        assert captured["json"]["temperature"] == 0
        assert captured["json"]["response_format"] == {"type": "json_object"}
        assert captured["json"]["model"] == ai_service.DEEPSEEK_INTENT_MODEL

    async def test_openai_request_uses_strict_schema_and_max_completion_tokens(self, monkeypatch):
        monkeypatch.setattr(ai_service, "ACTIVE_LLM_PROVIDER", "openai")
        resp = _mock_http_response(_openai_response(json.dumps({"intent": "leave_balance"})))
        captured = {}

        async def _fake_post(url, json=None, headers=None, **kwargs):
            captured["url"] = url
            captured["json"] = json
            return resp

        with patch.object(ai_service, "_http") as mock_http:
            mock_http.post = _fake_post
            await ai_service.classify_intent_structured(
                "prompt text", frozenset({"leave_balance", "apply_leave"}),
            )

        assert captured["url"] == ai_service.OPENAI_CHAT_URL
        assert captured["json"]["temperature"] == 0
        assert captured["json"]["model"] == ai_service.OPENAI_INTENT_MODEL
        # max_tokens (legacy) must NOT be sent — reasoning-tier models reject
        # it outright (the exact live bug already hit once on the non-HR
        # redirect path, see ai_service._call_openai_chat_stream's comment).
        assert "max_tokens" not in captured["json"]
        assert captured["json"]["max_completion_tokens"] == 30
        schema = captured["json"]["response_format"]["json_schema"]["schema"]
        assert set(schema["properties"]["intent"]["enum"]) == {"leave_balance", "apply_leave"}
        assert captured["json"]["response_format"]["json_schema"]["strict"] is True

    async def test_unknown_provider_falls_back_gracefully(self, monkeypatch):
        monkeypatch.setattr(ai_service, "ACTIVE_LLM_PROVIDER", "not-a-real-provider")
        label, usage, failed = await ai_service.classify_intent_structured(
            "prompt text", frozenset({"leave_balance"}), fallback_label="general_hr",
        )
        assert label == "general_hr"
        assert usage is None
        assert failed is True


async def _await(value):
    """Helper so MagicMock(return_value=...) can stand in for an async post()."""
    return value


class TestFullDatasetWiring:
    """One parametrized case per dataset entry — proves prompt-building
    never crashes and a correct model answer always round-trips intact.
    Does NOT test real model accuracy (see module docstring)."""

    @pytest.mark.parametrize(
        "case", INTENT_EVAL_DATASET, ids=[c["query"][:40] for c in INTENT_EVAL_DATASET]
    )
    async def test_prompt_builds_and_expected_label_round_trips(self, monkeypatch, case):
        monkeypatch.setattr(ai_service, "ACTIVE_LLM_PROVIDER", "deepseek")

        # Real prompt-building — must not raise for any real/authored query text.
        prompt = _build_intent_prompt(case["query"], recent=[], has_hr_context=False)
        assert case["query"] in prompt

        resp = _mock_http_response(_openai_response(json.dumps({"intent": case["intent"]})))
        with patch.object(ai_service, "_http") as mock_http:
            mock_http.post = MagicMock(return_value=_await(resp))
            label, _, _failed = await ai_service.classify_intent_structured(prompt, _VALID_INTENT_LABELS)

        assert label == case["intent"]

    def test_dataset_covers_every_valid_label(self):
        """Guards against the dataset silently losing coverage for a label
        as _VALID_INTENT_LABELS evolves — fails loudly instead of just having
        fewer parametrized cases run above."""
        covered = {c["intent"] for c in INTENT_EVAL_DATASET}
        missing = _VALID_INTENT_LABELS - covered
        assert not missing, f"No eval dataset coverage for: {sorted(missing)}"
