"""
Tests for:
  - GET /ping                    (cross-service health check, AC1/AC2/degradation)
  - Redis + Postgres session persistence via /hr-assist-stream (AC3)
  - Graceful handling of an OpenAI/DeepSeek connection drop (ai_service.py)

All external dependencies (PostgreSQL, Redis, erp-api, LLM calls) are mocked.
No real server, database, or network connection is needed to run these tests.
"""

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

import main
import services.ai_service as ai_service
import services.erp_client as erp_client
from services.erp_client import ErpApiTimeout, ErpApiUnavailable, ErpApiUnauthorized
from tests.conftest import TEST_COMPANY_ID, TEST_CONV_ID, FAKE_CONVERSATION
from tests.test_api import stream_mocks, collect_stream, _hr_astream  # noqa: F401 (fixture + helpers reuse)

AUTH_HEADER = {"Authorization": "Bearer caller-own-jwt-token"}


# ═════════════════════════════════════════════════════════════════════════════
# GET /ping
# ═════════════════════════════════════════════════════════════════════════════

class TestPing:

    async def test_ping_ok_forwards_callers_own_token(self, client):
        """erp-api reachable → 200, and the CALLER's own bearer token (not a
        stored service credential) is what gets forwarded — this is the
        literal evidence AC2 asks for. Redis is explicitly mocked healthy
        here (same pattern as test_ping_redis_down_degrades_without_
        changing_status_code below) — this module's own docstring promises
        no real server/database/network connection is needed to run these
        tests, so the "all ok" case must not silently depend on a real
        local Redis actually being reachable."""
        with patch("main.erp_client.ping") as mock_erp_ping, \
             patch("main._get_redis", return_value=MagicMock()):
            mock_erp_ping.return_value = {
                "latency_ms": 12.3, "http_status": 200, "body": {"success": True},
            }
            resp = await client.get("/ping", headers=AUTH_HEADER)

        assert resp.status_code == 200
        body = resp.json()
        assert body["status"] == "ok"
        assert "timestamp" in body
        assert body["dependencies"]["erp_api"]["status"] == "ok"
        assert body["dependencies"]["postgres"]["status"] == "ok"
        assert body["dependencies"]["redis"]["status"] == "ok"

        # The exact token from the Authorization header — not any stored secret.
        mock_erp_ping.assert_awaited_once()
        assert mock_erp_ping.await_args.args == ("caller-own-jwt-token",)

    async def test_ping_erp_timeout_returns_504(self, client):
        with patch("main.erp_client.ping", side_effect=ErpApiTimeout("timed out")):
            resp = await client.get("/ping", headers=AUTH_HEADER)

        assert resp.status_code == 504
        body = resp.json()["detail"]
        assert body["status"] == "degraded"
        assert body["dependencies"]["erp_api"]["error_code"] == "ERP_API_TIMEOUT"

    async def test_ping_erp_unreachable_returns_503(self, client):
        with patch("main.erp_client.ping", side_effect=ErpApiUnavailable("connection refused")):
            resp = await client.get("/ping", headers=AUTH_HEADER)

        assert resp.status_code == 503
        body = resp.json()["detail"]
        assert body["status"] == "degraded"
        assert body["dependencies"]["erp_api"]["error_code"] == "ERP_API_UNAVAILABLE"

    async def test_ping_redis_down_degrades_without_changing_status_code(self, client):
        """Redis outage must never flip the HTTP status — only erp-api does.
        The failure is surfaced as a specialized error_code, no crash."""
        with patch("main.erp_client.ping") as mock_erp_ping, \
             patch("main._get_redis", return_value=None):
            mock_erp_ping.return_value = {
                "latency_ms": 5.0, "http_status": 200, "body": {"success": True},
            }
            resp = await client.get("/ping", headers=AUTH_HEADER)

        assert resp.status_code == 200
        body = resp.json()
        assert body["status"] == "degraded"
        assert body["dependencies"]["redis"]["error_code"] == "REDIS_UNAVAILABLE"


# ═════════════════════════════════════════════════════════════════════════════
# AC3 — Redis + Postgres session persistence
# ═════════════════════════════════════════════════════════════════════════════

class TestSessionStatePersistence:

    async def test_hr_assist_stream_writes_to_redis_and_postgres(self, client, stream_mocks):
        """Driving one full turn through /hr-assist-stream must write the
        exchange to both the temporary Redis cache and the durable Postgres
        history — the existing production code path this story relies on
        for AC3, not new functionality."""
        with patch.object(main.hr_graph, "astream", side_effect=_hr_astream):
            await collect_stream(client, {
                "query": "What is the annual leave policy?",
                "conversation_id": TEST_CONV_ID,
            })

        # Redis (temporary session cache)
        stream_mocks["add_user_message"].assert_called_once()
        redis_user_args = stream_mocks["add_user_message"].call_args.args
        assert redis_user_args[0] == TEST_COMPANY_ID
        assert redis_user_args[1] == TEST_CONV_ID
        stream_mocks["add_ai_message"].assert_called_once()

        # Postgres (durable history)
        stream_mocks["save_message"].assert_called_once()
        pg_args = stream_mocks["save_message"].call_args.args
        assert pg_args[1] == TEST_CONV_ID
        assert pg_args[2] == TEST_COMPANY_ID


# ═════════════════════════════════════════════════════════════════════════════
# Graceful degradation — OpenAI/DeepSeek connection drop
#
# /hr-assist-stream can't surface a real HTTP 503/504 for an LLM failure: it's
# an SSE stream that has already sent 200 before any LLM call runs. Coverage
# here is at the ai_service.py layer instead — the failure must come back as
# a clean, typed exception, never an unhandled crash.
# ═════════════════════════════════════════════════════════════════════════════

class TestLlmConnectionDrop:

    async def test_deepseek_timeout_propagates_cleanly(self):
        with patch.object(ai_service, "_http") as mock_http:
            mock_http.post.side_effect = httpx.TimeoutException("connection timed out")
            with pytest.raises(httpx.TimeoutException):
                await ai_service._call_deepseek("ping")

    async def test_deepseek_connection_drop_propagates_cleanly(self):
        with patch.object(ai_service, "_http") as mock_http:
            mock_http.post.side_effect = httpx.ConnectError("connection dropped")
            with pytest.raises(httpx.ConnectError):
                await ai_service._call_deepseek("ping")


# ═════════════════════════════════════════════════════════════════════════════
# _check_postgres / _check_redis — direct unit tests
#
# Exercised indirectly by the TestPing cases above (via the real DATABASE_URL/
# REDIS_HOST env), but tested in isolation here so a broken Postgres/Redis
# connection string can't silently pass just because /ping's other mocks
# happen to compensate.
# ═════════════════════════════════════════════════════════════════════════════

class TestHealthCheckHelpers:

    def test_check_postgres_ok(self):
        mock_db = MagicMock()
        result = main._check_postgres(mock_db)
        assert result["status"] == "ok"
        assert isinstance(result["latency_ms"], float)

    def test_check_postgres_down_returns_degraded_with_error_code(self):
        mock_db = MagicMock()
        mock_db.execute.side_effect = Exception("connection refused")
        result = main._check_postgres(mock_db)
        assert result["status"] == "degraded"
        assert result["latency_ms"] is None
        assert result["error_code"] == "POSTGRES_UNAVAILABLE"

    def test_check_redis_ok(self):
        mock_client = MagicMock()
        with patch("main._get_redis", return_value=mock_client):
            result = main._check_redis()
        assert result["status"] == "ok"
        mock_client.ping.assert_called_once()

    def test_check_redis_unreachable_returns_degraded(self):
        with patch("main._get_redis", return_value=None):
            result = main._check_redis()
        assert result["status"] == "degraded"
        assert result["latency_ms"] is None
        assert result["error_code"] == "REDIS_UNAVAILABLE"

    def test_check_redis_ping_raises_returns_degraded(self):
        mock_client = MagicMock()
        mock_client.ping.side_effect = Exception("connection reset")
        with patch("main._get_redis", return_value=mock_client):
            result = main._check_redis()
        assert result["status"] == "degraded"
        assert result["error_code"] == "REDIS_UNAVAILABLE"


# ═════════════════════════════════════════════════════════════════════════════
# services/erp_client.py — direct unit tests
#
# TestPing above mocks erp_client.ping() wholesale at the main.py boundary;
# these tests instead exercise erp_client.ping()'s own logic — header
# forwarding, and the httpx-exception → typed-exception translation.
# ═════════════════════════════════════════════════════════════════════════════

class TestErpClient:

    async def test_ping_success_forwards_callers_bearer_token(self):
        fake_response = MagicMock()
        fake_response.status_code = 200
        fake_response.json.return_value = {"success": True, "message": "pong"}

        async def _request(method, url, headers=None, **kwargs):
            # patch.object on the whole client replaces .request with a plain
            # MagicMock, so give it an awaitable return explicitly.
            return fake_response

        with patch.object(erp_client, "ERP_API_URL", "http://erp.test"), \
             patch.object(erp_client, "_http") as mock_http:
            mock_http.request = _request
            result = await erp_client.ping("caller-token-abc")

        assert result["http_status"] == 200
        assert result["body"] == {"success": True, "message": "pong"}
        assert isinstance(result["latency_ms"], float)

    async def test_ping_forwards_exact_url_and_header(self):
        fake_response = MagicMock()
        fake_response.status_code = 200
        fake_response.json.return_value = {}
        captured = {}

        async def _request(method, url, headers=None, **kwargs):
            captured["method"] = method
            captured["url"] = url
            captured["headers"] = headers
            return fake_response

        with patch.object(erp_client, "ERP_API_URL", "http://erp.test"), \
             patch.object(erp_client, "_http") as mock_http:
            mock_http.request = _request
            await erp_client.ping("caller-token-abc")

        assert captured["method"] == "GET"
        assert captured["url"] == "http://erp.test/api/v1/ai/ping"
        assert captured["headers"]["Authorization"] == "Bearer caller-token-abc"

    async def test_ping_timeout_raises_erp_api_timeout(self):
        async def _request(*args, **kwargs):
            raise httpx.TimeoutException("timed out")

        with patch.object(erp_client, "ERP_API_URL", "http://erp.test"), \
             patch.object(erp_client, "_http") as mock_http:
            mock_http.request = _request
            with pytest.raises(ErpApiTimeout):
                await erp_client.ping("caller-token-abc")

    async def test_ping_connection_error_raises_erp_api_unavailable(self):
        async def _request(*args, **kwargs):
            raise httpx.ConnectError("connection refused")

        with patch.object(erp_client, "ERP_API_URL", "http://erp.test"), \
             patch.object(erp_client, "_http") as mock_http:
            mock_http.request = _request
            with pytest.raises(ErpApiUnavailable):
                await erp_client.ping("caller-token-abc")

    async def test_ping_5xx_raises_erp_api_unavailable(self):
        fake_response = MagicMock()
        fake_response.status_code = 500

        async def _request(*args, **kwargs):
            return fake_response

        with patch.object(erp_client, "ERP_API_URL", "http://erp.test"), \
             patch.object(erp_client, "_http") as mock_http:
            mock_http.request = _request
            with pytest.raises(ErpApiUnavailable):
                await erp_client.ping("caller-token-abc")

    async def test_ping_401_raises_erp_api_unauthorized(self):
        """A 401 from erp-api means the caller's own forwarded token was
        rejected there — distinct from erp-api being down, so it raises its
        own exception (ErpApiUnauthorized) rather than ErpApiUnavailable.
        main.py's /ping route still treats both as a dependency failure (see
        its combined except clause), but callers that care about the
        difference — like leave_eligibility_node — need them told apart."""
        fake_response = MagicMock()
        fake_response.status_code = 401

        async def _request(*args, **kwargs):
            return fake_response

        with patch.object(erp_client, "ERP_API_URL", "http://erp.test"), \
             patch.object(erp_client, "_http") as mock_http:
            mock_http.request = _request
            with pytest.raises(ErpApiUnauthorized):
                await erp_client.ping("caller-token-abc")

    async def test_ping_403_raises_erp_api_unavailable_not_a_silent_pass_through(self):
        """Regression guard: ping() must never treat an unexpected non-2xx
        status (anything but the 401/5xx cases above) as a false success —
        it has no business-error body to opt into, unlike the leave endpoints."""
        fake_response = MagicMock()
        fake_response.status_code = 403

        async def _request(*args, **kwargs):
            return fake_response

        with patch.object(erp_client, "ERP_API_URL", "http://erp.test"), \
             patch.object(erp_client, "_http") as mock_http:
            mock_http.request = _request
            with pytest.raises(ErpApiUnavailable):
                await erp_client.ping("caller-token-abc")

    async def test_ping_missing_erp_api_url_raises_without_network_call(self):
        called = {"count": 0}

        async def _request(*args, **kwargs):
            called["count"] += 1
            raise AssertionError("should never be called when ERP_API_URL is unset")

        with patch.object(erp_client, "ERP_API_URL", ""), \
             patch.object(erp_client, "_http") as mock_http:
            mock_http.request = _request
            with pytest.raises(ErpApiUnavailable):
                await erp_client.ping("caller-token-abc")

        assert called["count"] == 0

    async def test_ping_non_json_body_raises_erp_api_unavailable(self):
        """A 200 with a non-JSON body (proxy/HTML error page slipping through
        with a healthy status code) must not crash — same contract as every
        other erp-api failure mode."""
        fake_response = MagicMock()
        fake_response.status_code = 200
        fake_response.json.side_effect = ValueError("Expecting value: line 1 column 1 (char 0)")

        async def _request(*args, **kwargs):
            return fake_response

        with patch.object(erp_client, "ERP_API_URL", "http://erp.test"), \
             patch.object(erp_client, "_http") as mock_http:
            mock_http.request = _request
            with pytest.raises(ErpApiUnavailable):
                await erp_client.ping("caller-token-abc")

    # ── _request() — shared path used by get_leave_context/balance/apply/status ──

    async def test_request_404_raises_erp_api_unavailable(self):
        """Regression test: a 404 on these fixed, no-ID AI-leave routes only
        ever means the route itself isn't reachable (not deployed yet, wrong
        ERP_API_URL, proxy misroute) — never a per-resource result. Before
        this fix, 404 fell through to resp.json() and crashed the entire
        LangGraph run with an unhandled JSONDecodeError whenever erp-api
        returned a non-JSON 404 body — this is exactly what happened live
        when /api/v1/ai/leave/status 404'd against a deploy that predated
        the leave module."""
        fake_response = MagicMock()
        fake_response.status_code = 404
        fake_response.json.side_effect = ValueError("Expecting value: line 1 column 1 (char 0)")

        async def _request(*args, **kwargs):
            return fake_response

        with patch.object(erp_client, "ERP_API_URL", "http://erp.test"), \
             patch.object(erp_client, "_http") as mock_http:
            mock_http.request = _request
            with pytest.raises(ErpApiUnavailable):
                await erp_client.get_leave_status("caller-token-abc")

    async def test_request_non_json_body_on_200_raises_erp_api_unavailable(self):
        """Defense in depth beyond the 404 case above: ANY status code
        (including a nominally healthy 200) with a body that isn't valid
        JSON must raise ErpApiUnavailable, never propagate the raw
        JSONDecodeError up through leave_action_node."""
        fake_response = MagicMock()
        fake_response.status_code = 200
        fake_response.json.side_effect = ValueError("Expecting value: line 1 column 1 (char 0)")

        async def _request(*args, **kwargs):
            return fake_response

        with patch.object(erp_client, "ERP_API_URL", "http://erp.test"), \
             patch.object(erp_client, "_http") as mock_http:
            mock_http.request = _request
            with pytest.raises(ErpApiUnavailable):
                await erp_client.get_leave_balance("caller-token-abc")

    async def test_request_400_with_valid_json_still_passes_through(self):
        """Regression guard: erp-api's own 400 business-rule responses (e.g.
        'insufficient balance') must still surface as data, not be caught by
        the new 404/non-JSON handling — only genuinely undecodable bodies or
        404/401/5xx status codes should raise."""
        fake_response = MagicMock()
        fake_response.status_code = 400
        fake_response.json.return_value = {"success": False, "message": "Insufficient leave balance"}

        async def _request(*args, **kwargs):
            return fake_response

        with patch.object(erp_client, "ERP_API_URL", "http://erp.test"), \
             patch.object(erp_client, "_http") as mock_http:
            mock_http.request = _request
            result = await erp_client.get_leave_balance("caller-token-abc")

        assert result["http_status"] == 400
        assert result["body"] == {"success": False, "message": "Insufficient leave balance"}
