from services.memory import narrator_message_content, parse_narrator_message
from routers.chat import messages_for_llm
from services.rpg_state import format_narrator_outcome_for_llm


def test_messages_for_llm_includes_narrator_ruling_not_original_only():
    resolution = (
        "Luna's attempt backfires; people roll their eyes and an elderly man pats her head."
    )
    narrator_json = narrator_message_content(
        {
            "roll": 5,
            "outcome": "failure",
            "text": resolution,
            "original_intent": "bulldoze through the line",
        }
    )
    history = [
        {"role": "system", "content": "static"},
        {
            "role": "user",
            "content": "Луна влезла без очереди, распугивая всех",
            "action_resolution": {
                "intent_text": "Луна влезла без очереди",
                "roll": 5,
                "outcome": "failure",
                "resolution_text": resolution,
            },
        },
        {"role": "narrator", "content": narrator_json},
    ]
    llm = messages_for_llm(history, "system+runtime", rp_lang="en")
    user_msgs = [m for m in llm if m["role"] == "user"]
    assert len(user_msgs) == 2
    assert "canonical outcome" in user_msgs[0]["content"].lower()
    assert "Луна влезла" in user_msgs[0]["content"]
    assert "MANDATORY" in user_msgs[1]["content"]
    assert "backfires" in user_msgs[1]["content"]
    assert "Do NOT write a success version" in user_msgs[1]["content"]


def test_format_narrator_failure_wording_en():
    text = format_narrator_outcome_for_llm(
        {"roll": 5, "outcome": "failure", "text": "It failed."},
        lang="en",
    )
    assert "FAILED" in text
    assert "Do NOT write a success version" in text


def test_format_narrator_failure_wording_ru():
    text = format_narrator_outcome_for_llm(
        {"roll": 5, "outcome": "failure", "text": "Не вышло."},
        lang="ru",
    )
    assert "ОБЯЗАТЕЛЬНО" in text
    assert "Не удалось" in text or "НЕ удалось" in text


def test_parse_narrator_message_roundtrip():
    raw = narrator_message_content({"roll": 12, "outcome": "success", "text": "OK"})
    data = parse_narrator_message(raw)
    assert data["roll"] == 12
    assert data["text"] == "OK"
