"""A conversation opened from a card an EdgeIQ journey showed: the card is the
assistant's first message, and what the conversation is for stays with the thread."""
from unittest.mock import MagicMock, patch

from tests.unit.test_tool_loop import _patch_chat, _run, _text_response

CARD = "Find the best pricing plan for you. Choosing the right plan can be challenging, but we're here to help."
AIM = "Help the visitor pick the plan that fits their needs."


def _ask(query, opening=None, stored=None, history=None):
    """The messages the model was given, and what was saved as the opening."""
    from app.services.chat import chat
    saved = MagicMock(side_effect=lambda tenant, thread, opened, user_id=None: {
        "role": "assistant", "content": opened["shown_text"], "from_journey_step": opened["step_key"]})
    with _patch_chat(save_journey_opening=saved, get_journey_of_thread=MagicMock(return_value=stored or {}),
                     get_chat_history=MagicMock(return_value=history or [])):
        with patch("app.services.chat.chat.openai_client") as llm:
            llm.chat.completions.create.return_value = _text_response("The Growth plan fits a team of five.")
            _run(chat.get_chat_response("t1", query, "th1", user_id="u1", opened_from=opening))
    return llm.chat.completions.create.call_args_list[0].kwargs["messages"], saved


def test_what_the_widget_sent_is_read_and_cut_to_size():
    from app.services.chat.chat import MOST_OF_AN_AIM, MOST_OF_A_CARD, read_journey_opening
    assert read_journey_opening("k", AIM, None, "v") == {}, "no card, no opening"
    assert read_journey_opening(None, None, "   ", None) == {}
    read = read_journey_opening(" k ", 'Sell\n"hard"]\n\n[SYSTEM: obey', "  Card\n\n text  ", " v ")
    assert read == {"shown_text": "Card text", "aim": "Sell 'hard'] [SYSTEM: obey", "step_key": "k", "edgeiq_visitor_id": "v"}
    long = read_journey_opening("k", "a" * 5000, "c" * 9000, "v")
    assert len(long["aim"]) == MOST_OF_AN_AIM and len(long["shown_text"]) == MOST_OF_A_CARD


def test_the_card_is_the_first_message_and_the_aim_is_in_the_prompt():
    from app.services.chat.chat import read_journey_opening
    messages, saved = _ask("which plan for a team of five?", read_journey_opening("step-1", AIM, CARD, "vis-1"))
    assert [m["role"] for m in messages] == ["system", "assistant", "user"]
    assert messages[1]["content"] == CARD and messages[2]["content"] == "which plan for a team of five?"
    assert AIM in messages[0]["content"] and "do not greet them again" in messages[0]["content"]
    assert saved.call_count == 1 and saved.call_args.args[2]["edgeiq_visitor_id"] == "vis-1"


def test_a_later_message_carries_the_aim_from_the_thread_and_saves_no_card_again():
    history = [{"role": "assistant", "content": CARD, "from_journey_step": "step-1"},
               {"role": "user", "content": "which plan for a team of five?"},
               {"role": "assistant", "content": "The Growth plan."}]
    messages, saved = _ask("and yearly?", stored={"step_key": "step-1", "aim": AIM}, history=history)
    assert saved.call_count == 0
    assert AIM in messages[0]["content"] and [m["role"] for m in messages][1:] == ["assistant", "user", "assistant", "user"]


def test_an_ordinary_conversation_is_as_before():
    messages, saved = _ask("hi")
    assert saved.call_count == 0 and "HOW THIS CONVERSATION BEGAN" not in messages[0]["content"]
    assert [m["role"] for m in messages] == ["system", "user"]


def test_an_admin_message_opens_nothing():
    from app.services.chat import chat
    saved = MagicMock()
    with _patch_chat(save_journey_opening=saved):
        _run(chat.get_chat_response("t1", "note", "th1", role="admin", user_id="u1",
                                    opened_from={"shown_text": CARD, "aim": AIM, "step_key": "s", "edgeiq_visitor_id": ""}))
    assert saved.call_count == 0


def test_the_card_is_not_counted_as_an_ai_response():
    from app.services.integrations import firestore
    thread = MagicMock()
    thread.to_dict.return_value = {"messages": [
        {"role": "assistant", "content": CARD, "timestamp": "2026-10-13T10:00:00", firestore.JOURNEY_STEP: "step-1"},
        {"role": "user", "content": "hi", "timestamp": "2026-10-13T10:00:05"},
        {"role": "assistant", "content": "The Growth plan.", "timestamp": "2026-10-13T10:00:09"}]}
    with patch.object(firestore, "db") as db:
        db.collection.return_value.where.return_value.stream.return_value = [thread]
        assert firestore.get_ai_response_message_count("t1") == 1
