from masfactory.adapters.context.policy import DefaultContextPolicy
from masfactory.adapters.context.types import ContextBlock


def test_default_policy_provider_order_and_score_sorting():
    policy = DefaultContextPolicy()

    provider_blocks = [
        (
            "A",
            [
                ContextBlock(text="a0", score=0.1),
                ContextBlock(text="a1", score=0.9),
                ContextBlock(text="a2", score=None),
            ],
        ),
        (
            "B",
            [
                ContextBlock(text="b0", score=0.5),
                ContextBlock(text="b1", score=0.4),
            ],
        ),
    ]

    selected = policy.select(provider_blocks, top_k=10)

    assert [label for label, _ in selected] == ["A", "B"]
    assert [b.text for b in selected[0][1]] == ["a1", "a0", "a2"]
    assert [b.text for b in selected[1][1]] == ["b0", "b1"]


def test_default_policy_dedupe_prefers_dedupe_key_then_uri_chunk_then_text():
    policy = DefaultContextPolicy()

    provider_blocks = [
        (
            "A",
            [
                ContextBlock(text="same", dedupe_key="k1"),
                ContextBlock(text="same", dedupe_key="k1"),
                ContextBlock(text="u1", uri="file://x", chunk_id="1"),
                ContextBlock(text="u1_dup", uri="file://x", chunk_id="1"),
                ContextBlock(text="plain"),
                ContextBlock(text="plain"),
            ],
        )
    ]

    selected = policy.select(provider_blocks, top_k=100)
    blocks = selected[0][1]

    # Only one of each identity survives.
    assert [b.text for b in blocks] == ["same", "u1", "plain"]

