from langchain_core.messages import AIMessage, HumanMessage

from deerflow.agents.memory.thread_prompt import build_thread_memory_prompt, format_thread_memory_for_injection


def test_thread_memory_injection_keeps_profile_and_preferences_under_small_budget(monkeypatch):
    monkeypatch.setattr("deerflow.agents.memory.prompt._count_tokens", lambda text, encoding_name="cl100k_base": len(text))
    memory = {
        "user": {
            "workContext": {"summary": "Building APIs", "updatedAt": "2026-05-08T00:00:00Z"},
            "personalContext": {"summary": "Engineer using Python and React", "updatedAt": "2026-05-08T00:00:00Z"},
            "topOfMind": {"summary": "Improving thread memory", "updatedAt": "2026-05-08T00:00:00Z"},
        },
        "history": {
            "recentMonths": {"summary": "Shipped memory features", "updatedAt": "2026-05-08T00:00:00Z"},
            "earlierContext": {"summary": "Started from TS projects", "updatedAt": "2026-05-08T00:00:00Z"},
            "longTermBackground": {"summary": "Frontend developer", "updatedAt": "2026-05-08T00:00:00Z"},
        },
        "facts": [
            {"content": "Fact one that might be trimmed", "category": "context", "confidence": 0.9},
            {"content": "Fact two that might be trimmed", "category": "context", "confidence": 0.8},
        ],
    }

    result = format_thread_memory_for_injection(memory, max_tokens=140)
    assert "User Context:" in result
    assert "History:" in result


def test_build_thread_memory_prompt_does_not_raise_format_key_error():
    prompt = build_thread_memory_prompt(
        {"user": {}, "history": {}, "facts": []},
        [HumanMessage(content="My name is Alice.")],
    )
    assert "Current per-thread memory" in prompt
    assert '"user"' in prompt
    assert "Preferred memory language: same as the user's latest message" in prompt


def test_build_thread_memory_prompt_prefers_chinese_for_chinese_conversation():
    prompt = build_thread_memory_prompt(
        {"user": {}, "history": {}, "facts": []},
        [HumanMessage(content="我叫小明，我更喜欢中文交流。")],
    )
    assert "Preferred memory language: zh-Hans" in prompt


def test_build_thread_memory_prompt_prefers_japanese_for_japanese_conversation():
    prompt = build_thread_memory_prompt(
        {"user": {}, "history": {}, "facts": []},
        [HumanMessage(content="私は日本語で会話したいです。")],
    )
    assert "Preferred memory language: ja-JP" in prompt


def test_build_thread_memory_prompt_uses_user_messages_only_for_language_inference():
    prompt = build_thread_memory_prompt(
        {"user": {}, "history": {}, "facts": []},
        [
            HumanMessage(content="请用中文记录记忆"),
            AIMessage(content="Sure, I will answer in English with many many words."),
            AIMessage(content="More English content that should not change language inference."),
        ],
    )
    assert "Preferred memory language: zh-Hans" in prompt


def test_build_thread_memory_prompt_handles_structured_human_content():
    prompt = build_thread_memory_prompt(
        {"user": {}, "history": {}, "facts": []},
        [
            HumanMessage(
                content=[
                    {"type": "text", "text": "我希望记忆使用中文。"},
                    {"type": "text", "text": "请继续。"},
                ]
            ),
            AIMessage(content="I can also reply in English."),
        ],
    )
    assert "Preferred memory language: zh-Hans" in prompt
