DOCS = [
    ("D1", 0.98, "team-a"), ("D2", 0.94, "team-b"),
    ("D3", 0.85, "public"), ("D4", 0.70, "public"),
]


def contexts(principal, k):
    # A trusted application supplies the principal; not client authority.
    allowed = lambda d: d[2] == "public" or d[2] == principal
    ranked = sorted(DOCS, key=lambda d: -d[1])
    before = [d[0] for d in ranked if allowed(d)][:k]
    after = [d[0] for d in ranked[:k] if allowed(d)]
    return {"before": before, "after": after}


# Verification: underfilling and authorized-only final contexts.
assert contexts("public", 2) == {"before": ["D3", "D4"], "after": []}
assert contexts("team-a", 2) == {"before": ["D1", "D3"], "after": ["D1"]}
fixtures = []
for principal in ("public", "team-a", "team-b"):
    allowed_ids = {d[0] for d in DOCS if d[2] in ("public", principal)}
    for k in (1, 2, 3):
        value = contexts(principal, k)
        assert set(value["before"]) <= allowed_ids
        assert set(value["after"]) <= allowed_ids
        fixtures.append({"inputs": {"principal": principal, "k": str(k)},
                         "expected": value})

import json
print(json.dumps({"fixtures": fixtures, "checks_passed": True}))
