from services.rpg_facts import (
    FACTS_COMPRESS_SYSTEM,
    merge_facts,
    parse_facts_list,
    facts_to_prompt,
    facts_list_to_json,
    dedupe_facts_fuzzy,
    facts_are_similar,
    is_likely_narrative_event,
    filter_durable_facts,
    validate_compressed_against_source,
)


def test_legacy_string_facts():
    raw = '["Old fact", "Another"]'
    facts = parse_facts_list(raw)
    assert len(facts) == 2
    assert facts[0]["text"] == "Old fact"


def test_fuzzy_similar_near_duplicate():
    assert facts_are_similar(
        "Rin and Grigo found a magical glade with glowing flowers",
        "Rin and Grigo found magical glade glowing flowers",
    )


def test_dedupe_collapses_duplicates():
    raw = facts_list_to_json(
        [
            {"text": "Rin found a magical glade with glowing flowers", "rp_day": "day 1"},
            {"text": "Rin found magical glade glowing flowers", "rp_day": "day 1"},
            {"text": "Player name is Grigo", "rp_day": "day 1"},
        ]
    )
    out = dedupe_facts_fuzzy(parse_facts_list(raw))
    assert len(out) == 2


def test_facts_compress_system_format_escapes_json_braces():
    system = FACTS_COMPRESS_SYSTEM.format(target=22)
    assert "Target at most 22 facts" in system
    assert '{"text":' in system


def test_narrative_event_facts_filtered():
    assert is_likely_narrative_event("Сара и Григо отправились через портал")
    assert not is_likely_narrative_event("Сара носит красный спортивный костюм")
    facts = filter_durable_facts([
        {"text": "Сара любит шоколад", "rp_day": "день 1"},
        {"text": "Сара и Григо решили вызвать СОДП", "rp_day": "день 2"},
    ])
    assert len(facts) == 1


def test_validate_compressed_rejects_hallucinations():
    original = [{"text": "Сара любит шоколад", "rp_day": "день 1"}]
    compressed = [
        {"text": "Сара любит шоколад", "rp_day": "день 1"},
        {"text": "Сара — королева галактики", "rp_day": "день 9"},
    ]
    out = validate_compressed_against_source(original, compressed)
    assert len(out) == 1
    assert "шоколад" in out[0]["text"]


def test_merge_with_rp_day():
    existing = facts_list_to_json([{"text": "A", "rp_day": "день 1"}])
    merged = parse_facts_list(
        merge_facts(existing, [{"text": "B", "rp_day": ""}], rp_day_default="день 2")
    )
    assert merged[1]["rp_day"] == "день 2"
