"""
Regression tests for services/chat_service.py::get_full_history and its
_parse_ai_response_full helper.

Live bug: reopening a past conversation showed only plain text — the leave
balance/confirmation/status "modal" cards that render live during streaming
never appeared. save_message() DID persist the full structured payload (the
same 'data' object the stream's 'done' event carries — leave type, dates,
session, total days, leave_quota, the leaves list, etc.) into Message.
ai_response as JSON. But GET /conversations/{id} was reusing get_context(),
a function built to produce plain {role, content} pairs for feeding an LLM
prompt — it discards everything in 'data' except the flattened answer text.
get_full_history() is the fix: same query, but keeps intent + the full
'data' object per assistant turn.
"""

import json
from unittest.mock import MagicMock

from services.chat_service import _parse_ai_response_full, get_full_history


class TestParseAiResponseFull:

    def test_extracts_intent_and_full_data_from_json_string(self):
        raw = json.dumps({
            "success": True, "intent": "apply_leave",
            "data": {
                "answer": "To confirm: 1.0 day(s) of casual leave from 2026-09-01 to 2026-09-01. Shall I submit this request?",
                "leave_type": "casual_leave", "from_date": "2026-09-01", "to_date": "2026-09-01",
                "session_type_slug": "full_day", "total_days": 1.0,
            },
        })
        parsed = _parse_ai_response_full(raw)
        assert parsed["intent"] == "apply_leave"
        assert parsed["data"]["leave_type"] == "casual_leave"
        assert parsed["data"]["total_days"] == 1.0

    def test_handles_dict_input_not_just_json_string(self):
        raw = {"intent": "leave_balance", "data": {"answer": "...", "leave_quota": {"casual_leave": {"total": "7", "remaining": "5"}}}}
        parsed = _parse_ai_response_full(raw)
        assert parsed["intent"] == "leave_balance"
        assert parsed["data"]["leave_quota"]["casual_leave"]["remaining"] == "5"

    def test_missing_data_key_returns_empty_dict_not_none(self):
        parsed = _parse_ai_response_full(json.dumps({"intent": "leave_success"}))
        assert parsed["intent"] == "leave_success"
        assert parsed["data"] == {}

    def test_none_input_returns_none(self):
        assert _parse_ai_response_full(None) is None

    def test_malformed_json_returns_none_not_a_crash(self):
        assert _parse_ai_response_full("not valid json{{{") is None

    def test_double_encoded_json_string_is_unwrapped(self):
        # save_message double-json.dumps()s if the caller already passed a
        # string — must handle that without crashing.
        inner = json.dumps({"intent": "leave_status", "data": {"answer": "ok", "leaves": []}})
        outer = json.dumps(inner)
        parsed = _parse_ai_response_full(outer)
        assert parsed["intent"] == "leave_status"


def _fake_message(content, ai_response, created_at=None):
    m = MagicMock()
    m.content = content
    m.ai_response = ai_response
    m.created_at = created_at
    return m


def _mock_db_returning(rows):
    db = MagicMock()
    db.query.return_value.filter.return_value.order_by.return_value.limit.return_value.all.return_value = rows
    return db


class TestGetFullHistory:

    def test_returns_full_structured_data_for_a_leave_confirmation_turn(self):
        """This is the exact scenario from the live bug: an apply-leave
        confirmation card must survive a reload with its full data intact,
        not just the answer sentence."""
        ai_response = json.dumps({
            "success": True, "intent": "apply_leave",
            "data": {
                "answer": "To confirm: 0.5 day(s) of earned leave from 2026-08-24 to 2026-08-24. Shall I submit this request?",
                "leave_type": "earned_leave", "from_date": "2026-08-24", "to_date": "2026-08-24",
                "session_type_slug": "second_half_day", "total_days": 0.5,
            },
        })
        # Rows come back DESC (newest first) from the query — get_full_history reverses them.
        db = _mock_db_returning([_fake_message("half day", ai_response)])

        result = get_full_history(db, "conv-1", 99, limit=50)

        assert result[0] == {"role": "user", "content": "half day", "created_at": None}
        assistant_msg = result[1]
        assert assistant_msg["role"] == "assistant"
        assert assistant_msg["intent"] == "apply_leave"
        assert assistant_msg["data"]["leave_type"] == "earned_leave"
        assert assistant_msg["data"]["total_days"] == 0.5
        assert "Shall I submit" in assistant_msg["content"]

    def test_returns_leave_balance_quota_for_frontend_card(self):
        ai_response = json.dumps({"intent": "leave_balance", "data": {
            "answer": "Here's your current leave balance.",
            "leave_quota": {"casual_leave": {"total": "7", "remaining": "4.7"}},
        }})
        db = _mock_db_returning([_fake_message("what's my leave balance", ai_response)])

        result = get_full_history(db, "conv-1", 99, limit=50)

        assistant_msg = result[1]
        assert assistant_msg["intent"] == "leave_balance"
        assert assistant_msg["data"]["leave_quota"]["casual_leave"]["remaining"] == "4.7"

    def test_user_turn_with_no_ai_response_yet_is_still_included(self):
        db = _mock_db_returning([_fake_message("hello", None)])

        result = get_full_history(db, "conv-1", 99, limit=50)

        assert len(result) == 1
        assert result[0]["role"] == "user"

    def test_plain_chat_answer_has_no_intent_specific_data(self):
        ai_response = json.dumps({"intent": "leave_policy", "data": {"answer": "Casual leave is..."}})
        db = _mock_db_returning([_fake_message("what is casual leave", ai_response)])

        result = get_full_history(db, "conv-1", 99, limit=50)

        assistant_msg = result[1]
        assert assistant_msg["intent"] == "leave_policy"
        assert assistant_msg["content"] == "Casual leave is..."
