#!/usr/bin/env python3
"""Offline authorization fixture, not a vector database or identity provider."""
import json
import sys

def visible(document, user):
    if document.get("tenant") != user.get("tenant"):
        return False
    allowed = document.get("groups")
    groups = user.get("groups")
    if not isinstance(allowed, list) or not isinstance(groups, list):
        return False
    if not allowed or not all(isinstance(x, str) for x in allowed + groups):
        return False
    return bool(set(allowed).intersection(groups))

def retrieve(source):
    user = source["verifiedUser"]
    if not isinstance(user.get("tenant"), str) or not user["tenant"]:
        raise ValueError("a verified nonempty tenant is required")
    rows = source["documents"]
    # Real services must obtain this user from authenticated server-side context.
    # Never trust an arbitrary request-body tenant or model-generated group list.
    return [{"id": row["id"], "sourceVersion": row["sourceVersion"]}
            for row in rows if visible(row, user)]

def main():
    source = json.load(open(sys.argv[1], encoding="utf-8"))
    print(json.dumps({"permittedReferences": retrieve(source),
      "liveIdentityVerified": False}, indent=2))

if __name__ == "__main__":
    try:
        main()
    except (ValueError, KeyError, IndexError, OSError) as error:
        print(str(error), file=sys.stderr)
        sys.exit(2)
