#!/usr/bin/env python3
"""Fictional RAG metadata/ACL fixtures and an actual student-module grader.

Implement serve(state, session_id, request) in a separate file. Ranked rows are
simulation metadata, not embeddings or measured model/retrieval quality.
This public suite is not a confidential exam or an execution sandbox.
"""
import argparse
import copy
import hashlib
import importlib.util
import json
from pathlib import Path
import platform
import random
import sys


def fixture():
    state = {"authority_available": True, "policy_version": 3,
             "sessions": {"session-dev": {"tenant": "tenant-a", "user": "user-dev", "auth_version": 4, "groups": ["dev"]},
                          "session-fin": {"tenant": "tenant-a", "user": "user-fin", "auth_version": 7, "groups": ["finance"]}},
             "documents": {
                 "d-dev": {"tenant": "tenant-a", "source_version": 1, "acl_version": 2, "groups": ["dev"], "body": "development budget 10"},
                 "d-fin": {"tenant": "tenant-a", "source_version": 1, "acl_version": 5, "groups": ["finance"], "body": "finance budget 90"},
                 "d-other": {"tenant": "tenant-b", "source_version": 1, "acl_version": 2, "groups": ["dev"], "body": "other tenant budget 99"}},
             "ranked": [{"id": "d-fin", "source_version": 1, "acl_version": 5, "score": 0.99},
                        {"id": "d-other", "source_version": 1, "acl_version": 2, "score": 0.98},
                        {"id": "d-dev", "source_version": 1, "acl_version": 2, "score": 0.7}],
             "cache": {"cache-fin": {"tenant": "tenant-a", "user": "user-fin", "auth_version": 7,
                                      "policy_version": 3, "body": "finance summary 90",
                                      "dependencies": [{"id": "d-fin", "source_version": 1, "acl_version": 5}]}}}
    return state


def cases(seed):
    state = fixture(); out = []
    def add(name, s, session, request, expected=None, error=None):
        out.append((name, copy.deepcopy([s, session, request]), expected, error))
    def result(doc, body, hit=False):
        return {"items": [{"id": doc, "body": body}], "cache_hit": hit}
    empty = {"items": [], "cache_hit": False}
    dev = result("d-dev", "development budget 10")
    fin = result("d-fin", "finance budget 90")
    dev_ref = {"id": "d-dev", "source_version": 1, "acl_version": 2}
    fin_ref = {"id": "d-fin", "source_version": 1, "acl_version": 5}
    add("retrieve_filter_before_limit", state, "session-dev", {"kind": "retrieve", "limit": 1}, dev)
    add("untrusted_request_groups_ignored", state, "session-dev", {"kind": "retrieve", "limit": 1, "groups": ["finance"], "tenant": "tenant-b"}, dev)
    add("context_expansion_filters_and_deduplicates", state, "session-dev", {"kind": "context", "refs": [fin_ref, dev_ref, dev_ref]}, dev)
    add("by_id_denied", state, "session-dev", {"kind": "by_id", "id": "d-fin"}, empty)
    add("citation_denied", state, "session-dev", {"kind": "citation", "ref": fin_ref}, empty)
    add("positive_by_id", state, "session-fin", {"kind": "by_id", "id": "d-fin"}, fin)
    add("positive_citation", state, "session-fin", {"kind": "citation", "ref": fin_ref}, fin)
    add("positive_cache", state, "session-fin", {"kind": "cache", "cache_id": "cache-fin"}, result("cache-fin", "finance summary 90", True))
    add("cache_cross_user", state, "session-dev", {"kind": "cache", "cache_id": "cache-fin"}, empty)
    add("unknown_session", state, "missing-session", {"kind": "by_id", "id": "d-dev"}, empty)
    add("unknown_document", state, "session-dev", {"kind": "by_id", "id": "missing"}, empty)
    revoked = copy.deepcopy(state); revoked["sessions"]["session-fin"].update(groups=[], auth_version=8)
    for kind, request in [("retrieve", {"kind": "retrieve", "limit": 3}),
                          ("context", {"kind": "context", "refs": [fin_ref]}),
                          ("by_id", {"kind": "by_id", "id": "d-fin"}),
                          ("citation", {"kind": "citation", "ref": fin_ref}),
                          ("cache", {"kind": "cache", "cache_id": "cache-fin"})]:
        add("revoked_" + kind, revoked, "session-fin", request, empty)
        unavailable = copy.deepcopy(state); unavailable["authority_available"] = False
        add("authority_unavailable_" + kind, unavailable, "session-fin", request, empty)
    restored = copy.deepcopy(revoked); restored["sessions"]["session-fin"].update(groups=["finance"], auth_version=9)
    add("regrant_does_not_revive_cache_generation", restored, "session-fin", {"kind": "cache", "cache_id": "cache-fin"}, empty)
    changed = copy.deepcopy(state); changed["documents"]["d-fin"]["source_version"] = 2
    add("derived_cache_source_changed", changed, "session-fin", {"kind": "cache", "cache_id": "cache-fin"}, empty)
    add("old_citation_source_changed", changed, "session-fin", {"kind": "citation", "ref": fin_ref}, empty)
    add("stale_index_source", changed, "session-fin", {"kind": "retrieve", "limit": 3}, empty)
    changed = copy.deepcopy(state); changed["documents"]["d-fin"]["acl_version"] = 6
    add("derived_cache_acl_changed", changed, "session-fin", {"kind": "cache", "cache_id": "cache-fin"}, empty)
    add("old_context_acl_changed", changed, "session-fin", {"kind": "context", "refs": [fin_ref]}, empty)
    add("stale_index_acl", changed, "session-fin", {"kind": "retrieve", "limit": 3}, empty)
    changed = dict(state, policy_version=4)
    add("cache_policy_changed", changed, "session-fin", {"kind": "cache", "cache_id": "cache-fin"}, empty)
    add("missing_limit", state, "session-dev", {"kind": "retrieve"}, error="shape")
    add("boolean_limit", state, "session-dev", {"kind": "retrieve", "limit": True}, error="shape")
    add("null_refs", state, "session-dev", {"kind": "context", "refs": None}, error="shape")
    add("null_session", state, None, {"kind": "by_id", "id": "d-dev"}, error="shape")
    add("unknown_kind", state, "session-dev", {"kind": "answer"}, error="shape")
    changed = copy.deepcopy(state); changed["sessions"]["session-dev"]["groups"] = None
    add("null_trusted_groups", changed, "session-dev", {"kind": "retrieve", "limit": 1}, error="shape")
    changed = copy.deepcopy(state); changed["ranked"][0]["score"] = float("inf")
    add("rank_score_must_be_finite", changed, "session-dev", {"kind": "retrieve", "limit": 1}, error="shape")
    both = copy.deepcopy(state); both["sessions"]["session-dev"]["groups"] = ["dev", "finance"]
    add("context_keeps_first_requested_order", both, "session-dev", {"kind": "context", "refs": [dev_ref, fin_ref, dev_ref]}, {"items": dev["items"] + fin["items"], "cache_hit": False})
    both["ranked"][2]["score"] = 0.99
    add("equal_scores_tie_break_by_id", both, "session-dev", {"kind": "retrieve", "limit": 2}, {"items": dev["items"] + fin["items"], "cache_hit": False})
    # Filter current authorization/versions first; duplicate IDs use the highest
    # valid score, then sort descending by that score and ascending by ID.
    duplicate = copy.deepcopy(both)
    duplicate["ranked"] = [dict(dev_ref, score=0.2), dict(fin_ref, score=0.6), dict(dev_ref, score=0.9)]
    add("duplicate_id_highest_valid_score", duplicate, "session-dev", {"kind": "retrieve", "limit": 1}, dev)
    duplicate["ranked"] = [dict(dev_ref, acl_version=1, score=0.99),
                           {"id": "d-other", "source_version": 1, "acl_version": 2, "score": 0.98},
                           dict(dev_ref, score=0.2), dict(fin_ref, score=0.6),
                           {"id": "d-other", "source_version": 1, "acl_version": 2, "score": 0.97}]
    add("stale_and_unauthorized_duplicates_filtered_before_scoring", duplicate, "session-dev",
        {"kind": "retrieve", "limit": 1}, fin)
    # Every cache dependency matters, including ones after a usable first row.
    mixed = copy.deepcopy(state)
    mixed["cache"]["cache-mixed"] = {"tenant": "tenant-a", "user": "user-dev", "auth_version": 4,
        "policy_version": 3, "body": "combined budgets 10 and 90", "dependencies": [dev_ref, fin_ref]}
    add("cache_second_dependency_unauthorized", mixed, "session-dev", {"kind": "cache", "cache_id": "cache-mixed"}, empty)
    mixed["sessions"]["session-dev"]["groups"] = ["dev", "finance"]
    add("cache_two_current_dependencies_allowed", mixed, "session-dev", {"kind": "cache", "cache_id": "cache-mixed"},
        result("cache-mixed", "combined budgets 10 and 90", True))
    mixed["cache"]["cache-mixed"]["dependencies"][1]["acl_version"] = 4
    add("cache_second_dependency_acl_stale", mixed, "session-dev", {"kind": "cache", "cache_id": "cache-mixed"}, empty)
    rng = random.Random(seed)
    for i in range(4):
        tag = f"v-{rng.randrange(10000, 99999)}-{i}"; v = rng.randrange(2, 20)
        s = fixture(); session = tag + "-session"; did = tag + "-doc"; cid = tag + "-cache"
        s["sessions"] = {session: {"tenant": tag + "-tenant", "user": tag + "-user", "auth_version": v, "groups": [tag + "-group"]}}
        s["documents"] = {did: {"tenant": tag + "-tenant", "source_version": v, "acl_version": v + 1, "groups": [tag + "-group"], "body": tag + "-body"}}
        ref = {"id": did, "source_version": v, "acl_version": v + 1}
        s["ranked"] = [dict(ref, score=0.9)]
        s["cache"] = {cid: {"tenant": tag + "-tenant", "user": tag + "-user", "auth_version": v, "policy_version": 3, "body": tag + "-summary", "dependencies": [ref]}}
        add(f"variant_{i}_positive", s, session, {"kind": "retrieve", "limit": 1}, result(did, tag + "-body"))
        stale = copy.deepcopy(s); stale["documents"][did]["acl_version"] += 1
        add(f"variant_{i}_stale_context", stale, session, {"kind": "context", "refs": [ref]}, empty)
        changed = copy.deepcopy(s); changed["sessions"][session]["groups"] = []; changed["sessions"][session]["auth_version"] += 1
        add(f"variant_{i}_revoked_cache", changed, session, {"kind": "cache", "cache_id": cid}, empty)
    return out


def strict_equal(left, right):
    if type(left) is not type(right): return False
    if isinstance(right, dict):
        return left.keys() == right.keys() and all(strict_equal(left[k], v) for k, v in right.items())
    if isinstance(right, list):
        return len(left) == len(right) and all(strict_equal(x, y) for x, y in zip(left, right))
    return left == right


def grade(path, seed):
    path = Path(path).resolve()
    report = {"mode": "student", "module": str(path), "seed": seed, "python": platform.python_version(),
              "guided_credit": False, "suite_is_public": True, "cases": []}
    try:
        report["module_sha256"] = hashlib.sha256(path.read_bytes()).hexdigest()
        spec = importlib.util.spec_from_file_location("student_rag_acl", path)
        module = importlib.util.module_from_spec(spec)
        sys.modules[spec.name] = module
        spec.loader.exec_module(module)
    except Exception as exc:
        report.update(passed=False, error=f"import:{type(exc).__name__}:{exc}"); return report
    for name, inputs, expected, error in cases(seed):
        before = copy.deepcopy(inputs); got = None; raised = None
        try: got = module.serve(*inputs)
        except Exception as exc: raised = f"{type(exc).__name__}:{exc}"
        ok = (raised == f"ValueError:{error}") if error else (raised is None and strict_equal(got, expected))
        unchanged = strict_equal(inputs, before)
        report["cases"].append({"name": name, "passed": ok and unchanged, "input_unchanged": unchanged,
                                "expected_error": error, "expected": expected, "got": got if raised is None else raised})
    report["passed_count"] = sum(c["passed"] for c in report["cases"]); report["total_count"] = len(report["cases"])
    report["passed"] = report["passed_count"] == report["total_count"]
    return report


def main():
    parser = argparse.ArgumentParser(description=__doc__); sub = parser.add_subparsers(dest="mode", required=True)
    sub.add_parser("fixture"); sub.add_parser("guided"); sub.add_parser("incident")
    p = sub.add_parser("scaffold"); p.add_argument("--out", required=True)
    p = sub.add_parser("grade"); p.add_argument("--module", dest="student", required=True); p.add_argument("--out", required=True); p.add_argument("--seed", type=int, default=41)
    p = sub.add_parser("explain"); p.add_argument("--diagnosis", required=True); p.add_argument("--diff", required=True)
    args = parser.parse_args(); state = fixture()
    if args.mode == "scaffold":
        target = Path(args.out)
        try:
            with target.open("x", encoding="utf-8") as stream:
                stream.write('"""Implement the published five-entry authorization contract yourself."""\n\ndef serve(state, session_id, request):\n    raise NotImplementedError("implement serve")\n')
        except FileExistsError:
            print(json.dumps({"error": "refusing_to_overwrite", "path": str(target)})); return 1
        print(json.dumps({"created": str(target), "solution_supplied": False})); return 0
    if args.mode == "grade":
        output = grade(args.student, args.seed)
        Path(args.out).write_text(json.dumps(output, ensure_ascii=False, indent=2, default=repr) + "\n", encoding="utf-8")
        print(json.dumps({"report": args.out, "passed": output["passed"], "passed_count": output.get("passed_count", 0), "total_count": output.get("total_count", 0), "module_sha256": output.get("module_sha256")}))
        return 0 if output["passed"] else 1
    if args.mode == "fixture": output = state
    elif args.mode == "guided":
        # One metadata observation; not the student's five-entry implementation.
        session = state["sessions"]["session-dev"]
        allowed = sorted(did for did, d in state["documents"].items()
                         if d["tenant"] == session["tenant"] and set(d["groups"]) & set(session["groups"]))
        output = {"mode": "guided", "allowed_document_ids": allowed, "real_vector_or_model_measurement": False}
    elif args.mode == "incident":
        output = {"mode": "public_diagnostic_rehearsal", "events": [
            {"step": "membership_revoke", "session": "session-fin", "auth_version": 8, "groups": []},
            {"step": "cache", "cache_auth_version": 7, "cache_hit": True, "body": "finance summary 90", "current_acl_checked": False},
            {"step": "citation", "document": "d-fin", "body": "finance budget 90", "entry_acl_checked": False}],
            "fault_fragments": ["cache: return state['cache'][request['cache_id']]['body']",
                                "citation: return state['documents'][request['ref']['id']]['body']"],
            "next": "Record your causal diagnosis and code diff before optional explain."}
    else:
        paths = [Path(args.diagnosis), Path(args.diff)]
        if any(not p.is_file() or not p.read_text().strip() for p in paths):
            print(json.dumps({"error": "nonempty diagnosis and diff files required"})); return 1
        output = {"mode": "optional_explanation", "submitted_sha256": {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in paths},
                  "explanation": "A hit is not current authorization. Authenticate by trusted session lookup at each entry; check current tenant/groups and all source/ACL versions before any document or derived body is returned. Old cache auth generations stay invalid after revoke and regrant. Hiding the final answer cannot undo prior disclosure. File presence is not a semantic diagnosis assessment."}
    print(json.dumps(output, ensure_ascii=False, indent=2)); return 0


if __name__ == "__main__": sys.exit(main())
