"""Developer tools: a diagram of the policy (Mermaid), and the clients `rowstile client` writes: a typed client for
Python and for TypeScript (or the names alone, for an app on the TypeScript SDK), the policy's names for the other
SDKs (Go, C#, Ruby and their signatures, Java, Rust, Elixir, PHP), and for the sync engines Electric's shapes,
Zero's tables and filters, and PowerSync's streams."""

from __future__ import annotations

import json
import re
from collections.abc import Callable, Mapping
from typing import TypeAlias

from .parse import And, Arrow, Cond, Expr, Not, Or, Perm, Ref, Type
from .sqlutil import q
from .sync import SyncMixin

# what the clients are made from: {type: [permission]}, {type: {relation: [subject]}}, [scope]
Perms: TypeAlias = "dict[str, list[str]]"
Shared: TypeAlias = "dict[str, dict[str, list[str]]]"


# the Java names' class when nothing names one: its file's name, in no package
JAVA_CLASS = "AuthzNames"
# the Elixir names' module when nothing names one
ELIXIR_MODULE = "Authz"


def _java_constant(name: str) -> str:
    """A name of the policy as a Java constant: orgUnit and org_unit are ORG_UNIT."""
    return re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", name).upper()


def _client_php(perms: Perms, source_name: str) -> str:
    """For apps on the PHP SDK (rowstile/rowstile): each type's permissions as an enum of their own, in the namespace
    Authz, which the SDK's calls take: a misspelled type or permission fails PHPStan, and PHP when the line runs. Names
    in PascalCase (note's break_glass is NotePermission::BreakGlass). Two names PHP would spell the same (editAll and
    edit_all) get neither, and a comment says why; so does one that isn't a PHP name (_9), or Class (::class is
    PHP's)."""

    def pascal(name: str) -> str:  # org_unit and orgUnit: OrgUnit
        return "".join(w[:1].upper() + w[1:] for w in name.split("_"))

    def named(name: str) -> bool:
        return bool(re.fullmatch(r"[A-Za-z_]\w*", name)) and name.lower() != "class"

    def unnamed(same: list[str], name: str) -> str:
        """Why the policy's names `same` have none in PHP."""
        if len(same) > 1:
            return f"{' and '.join(same)} would both be {name}: neither has one"
        return f"{same[0]} would be {name}, which isn't a name PHP takes: it has none"

    enums: dict[str, list[str]] = {}
    for t in perms:
        enums.setdefault(pascal(t) + "Permission", []).append(t)
    out: list[str] = []
    for t, ps in perms.items():
        enum = pascal(t) + "Permission"
        if len(enums[enum]) > 1 or not named(enum):
            if enums[enum][0] == t:
                out += ["", f"// {unnamed(enums[enum], enum)}"]
            continue
        cases: dict[str, list[str]] = {}
        for p in ps:
            cases.setdefault(pascal(p), []).append(p)
        body = [f"    // {unnamed(same, case)}" for case, same in cases.items() if len(same) > 1 or not named(case)]
        body += [f"    case {case} = '{same[0]}';" for case, same in cases.items() if len(same) == 1 and named(case)]
        out += [
            "",
            f"/** The permissions of {t}. */",
            f"enum {enum}: string implements Permission",
            "{",
            *body,
            "",
            "    public static function objectType(): string",
            "    {",
            f"        return '{t}';",
            "    }",
            "}",
        ]
    head = [
        "<?php",
        "",
        f"// Generated by rowstile client from {source_name}. Do not edit; re-run after changing the policy.",
        "// The policy's names, for the PHP SDK (rowstile/rowstile): each type's permissions an enum of their own, which",
        "// the SDK's calls take, so a misspelled one fails PHPStan, and PHP when the line runs. Composer loads this file:",
        '// list it in composer.json\'s autoload "files".',
        "",
        "declare(strict_types=1);",
        "",
        "namespace Authz;",
        "",
        "use Rowstile\\Permission;",
    ]
    return "\n".join(head + out) + "\n"


def _client_java(perms: Perms, java_class: str, source_name: str) -> str:
    """For apps on the Java SDK (dev.rowstile): the policy's names, a constant for each type and an enum of each
    type's permissions, so that a misspelled type or permission doesn't compile. Two names Java would spell the same
    (doc and Doc, editAll and edit_all) get neither, and a comment says why; so does `_`, a keyword in Java."""
    package, _, name = java_class.rpartition(".")

    def enum(t: str) -> str:
        return t[:1].upper() + t[1:] + "Permission"

    spelled: dict[str, list[str]] = {}
    for t in perms:
        for key in {_java_constant(t), enum(t)}:
            spelled.setdefault(key, []).append(t)
    types: list[str] = []
    enums: list[str] = []
    for t, ps in perms.items():
        same = sorted({o for key in (_java_constant(t), enum(t)) for o in spelled[key]})
        if len(same) > 1 or _java_constant(t) == "_":
            if t == same[0]:
                types.append(f"    // {' and '.join(same)}: no name in Java (one spelling, or _): ObjectType.of(name)")
            continue
        types.append(f"    public static final ObjectType<{enum(t)}> {_java_constant(t)} =")
        types.append(f'            ObjectType.of("{t}", {enum(t)}.class);')
        constants: dict[str, list[str]] = {}
        for p in ps:
            constants.setdefault(_java_constant(p), []).append(p)
        lines = [
            f'        // {" and ".join(named)}: no name in Java (one spelling, or _): Permission.of("{t}", name)'
            for c, named in constants.items()
            if len(named) > 1 or c == "_"
        ]
        values = [f'        {c}("{named[0]}")' for c, named in constants.items() if len(named) == 1 and c != "_"]
        body = "\n".join([*lines, ",\n".join(values) + ";"])
        enums.append(f"""
    /** The permissions of {t}. */
    public enum {enum(t)} implements Permission {{
{body}

        private final String name;

        {enum(t)}(String name) {{
            this.name = name;
        }}

        @Override
        public String type() {{
            return "{t}";
        }}

        @Override
        public String permission() {{
            return name;
        }}
    }}
""")
    head = f"package {package};\n\n" if package else ""
    constants_text = "\n".join(types)
    return f"""// Generated by rowstile client from {source_name}. Do not edit; re-run after changing the policy.
{head}import dev.rowstile.ObjectType;
import dev.rowstile.Permission;

/** The policy's names, for the SDK (dev.rowstile): a misspelled type or permission doesn't compile. */
public final class {name} {{
    private {name}() {{}}

{constants_text}
{"".join(enums)}}}
"""


def _client_rust(perms: Perms, source_name: str) -> str:
    """For apps on the Rust SDK (the rowstile crate): the policy's names as a module, a constant for each type and an
    enum of each type's permissions, implementing rowstile::Permission, which the SDK's calls take: a misspelled name
    doesn't compile, and neither does a plain string. Names in Rust's spelling: note's edit is NotePermission::Edit,
    org_unit's constant ORG_UNIT; two names Rust would spell the same get neither, and a comment says why; so does
    one Rust can't spell (_, or Self for a permission: a keyword)."""

    def camel(name: str) -> str:  # org_unit and orgUnit: OrgUnit
        return "".join(w[:1].upper() + w[1:] for w in name.split("_"))

    def unnamed(names: list[str], spelled: str) -> str:
        if len(names) > 1:
            return f"// {' and '.join(names)} would both be {spelled} in Rust: neither has a name here"
        return f"// {names[0]} can't be spelled in Rust: it has no name here"

    by: dict[str, list[str]] = {}  # a Rust name (a constant, an enum): the types it would stand for
    for t in perms:
        for key in (_java_constant(t), camel(t) + "Permission"):
            by.setdefault(key, []).append(t)
    q: Callable[[str], str] = lambda s: json.dumps(s)
    out = [
        f"// Generated by rowstile client from {source_name}. Do not edit; re-run after changing the policy.",
        "",
        "//! The policy's names, for the rowstile crate: a constant for each type, and an enum of each type's",
        "//! permissions, which `can`, `perms_of` and `list` take. A misspelled name doesn't compile, and neither",
        "//! does a plain string where the SDK takes a permission.",
        "#![allow(dead_code)]",
    ]
    for t, ps in perms.items():
        same = sorted({o for key in (_java_constant(t), camel(t) + "Permission") for o in by[key]})
        if len(same) > 1 or not camel(t):
            if t == same[0]:
                out += ["", unnamed(same, camel(t) + "Permission")]
            continue
        enum = camel(t) + "Permission"
        variants: dict[str, list[str]] = {}
        for p in ps:
            variants.setdefault(camel(p), []).append(p)
        named = {v: names[0] for v, names in variants.items() if len(names) == 1 and v not in ("", "Self")}
        out += [
            "",
            f"/// The type {t}.",
            f"pub const {_java_constant(t)}: &str = {q(t)};",
            "",
            f"/// The permissions of {t}.",
            "#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]",
            f"pub enum {enum} {{",
            *(f"    {unnamed(names, v)}" for v, names in variants.items() if v not in named),
        ]
        for v, p in named.items():
            out += [f"    /// {t}'s {p}.", f"    {v},"]
        out += [
            "}",
            "",
            f"impl rowstile::Permission for {enum} {{",
            f"    const OBJECT_TYPE: &'static str = {q(t)};",
            "",
            "    fn name(self) -> &'static str {",
            "        match self {" + ("" if named else "}"),
            *(f"            Self::{v} => {q(p)}," for v, p in named.items()),
            *(["        }"] if named else []),
            "    }",
            "",
            f"    fn from_name({'name' if named else '_'}: &str) -> Option<Self> {{",
            *(
                ["        match name {", *(f"            {q(p)} => Some(Self::{v})," for v, p in named.items())]
                + ["            _ => None,", "        }"]
                if named
                else ["        None"]
            ),
            "    }",
            "}",
        ]
    return "\n".join(out) + "\n"


def _id(*parts: str) -> str:
    """A node's id in the diagram: a type's name and a relation's or permission's, joined by `__`. A name the policy
    declares neither holds `__` nor starts or ends with `_` (AZ107), so two of them never share an id (`team` +
    `member_view`, `team_member` + `view`), as the views' names don't."""
    return "__".join(re.sub(r"[^A-Za-z0-9_]", "_", p) for p in parts)


def _box(type_name: str) -> str:
    """The id of a type's box: no relation or permission is named `0` (a name doesn't start with a digit)."""
    return _id(type_name, "0")


def _special(name: str) -> str:
    """The id of the `anyone` and `link` circles."""
    return _id(name, "1")


def _label(text: str) -> str:
    return text.replace('"', "'")


class DevMixin(SyncMixin):
    # ------------------------------------------------------------------
    # diagram
    # ------------------------------------------------------------------
    def graph(self) -> str:
        """A Mermaid flowchart: types, their relations (boxes) and permissions (rounded),
        what each permission is made of, and where relations point."""
        out = [
            "%% Generated by rowstile graph. Paste into any Mermaid viewer (GitHub renders it in ```mermaid blocks).",
            "flowchart LR",
            "  classDef perm fill:#e8f0fe,stroke:#4a6fd1,color:#1b2a4a",
            "  classDef rel fill:#f6f6f6,stroke:#888,color:#222",
            "  classDef user fill:#fff4e0,stroke:#d19a4a,color:#4a2f0b",
        ]
        edges: list[str] = []
        specials: set[str] = set()
        # the user type has a box when it has relations or permissions of its own; else it is a circle alone
        user = self.types.get("user")
        user_boxed = user is not None and bool(user.perms or user.relations)
        for t in self.types.values():
            if t.name == "user" and not user_boxed:
                out.append('  user(("user")):::user')
                continue
            out.append(f'  subgraph {_box(t.name)}["{_label(t.name)} · {_label(t.table)}"]')
            if t.name == "user":
                out.append('    user(("user")):::user')
            for r in t.relations.values():
                roles = r.sources[0]
                label = f"custom roles → {roles.perm}" if r.synthetic and roles.kind == "roles" else r.name
                out.append(f'    {_id(t.name, r.name)}["{_label(label)}"]:::rel')
                for src in r.sources:
                    if src.kind == "column":
                        col = src.column if isinstance(src.column, str) else "[" + ", ".join(src.column) + "]"
                        how = f"({src.type_col}, {col})" if src.type_col else col
                    else:
                        how = src.table if src.kind == "table" else src.kind
                    for st, sr in src.subjects:
                        drawn = st in self.types and (st != "user" or user_boxed)  # its box is there
                        if st in ("anyone", "link"):
                            target = _special(st)
                            specials.add(st)
                            lab = how
                        elif sr == "*":
                            # everyone of the type who is signed in: the user, or the type's box
                            target = "user" if st == "user" else _box(st)
                            lab = how + (" (everyone)" if st == "user" else f" (every {st})")
                        elif sr and drawn:
                            target = _id(st, sr)
                            lab = how
                        elif st == "user":
                            target = "user"
                            lab = how
                        else:
                            target = _box(st)
                            lab = how
                        style = "-.->" if src.kind in ("shared", "roles") else "-->"
                        edges.append(f'  {_id(t.name, r.name)} {style}|"{_label(lab)}"| {target}')
            for p in t.perms.values():
                label = p.name.replace("__base", ", before the deny") if p.hidden else p.name
                out.append(f'    {_id(t.name, p.name)}(["{_label(label)}"]):::perm')
                self._graph_expr(t, p, p.expr, edges, negated=False, cond=False)
            out.append("  end")
        out += [f'  {_special(st)}(("{st}")):::user' for st in sorted(specials)]
        return "\n".join(out + list(dict.fromkeys(edges))) + "\n"

    def _graph_expr(self, t: Type, p: Perm, node: Expr, edges: list[str], negated: bool, cond: bool) -> None:
        src = _id(t.name, p.name)

        def is_cond(n: Expr) -> bool:
            match n:
                case Cond(_):
                    return True
                case Not(inner):
                    return is_cond(inner)
            return False

        match node:
            case Or(items) | And(items):
                has_cond = cond or (isinstance(node, And) and any(is_cond(n) for n in items))
                for n in items:
                    self._graph_expr(t, p, n, edges, negated, has_cond)
            case Not(inner):
                self._graph_expr(t, p, inner, edges, not negated, cond)
            case Ref(name):
                lab = ("not" if negated else "") + (" if {…}" if cond else "")
                arrow = f'-.->|"{lab.strip()}"|' if lab else "-->"
                edges.append(f"  {src} {arrow} {_id(t.name, name)}")
            case Arrow(rel, perm):
                r = t.relations.get(rel)
                targets = [st for st, sr in r.subjects() if not sr] if r else []
                lab = rel + (" · not" if negated else "") + (" · if {…}" if cond else "")
                for st in targets:
                    edges.append(f'  {src} ==>|"{_label(lab)}"| {_id(st, perm)}')

    # ------------------------------------------------------------------
    # client helpers
    # ------------------------------------------------------------------
    def _client_model(self) -> tuple[Perms, Shared, list[str]]:
        perms = {t.name: self.public_perms(t) for t in self.types.values() if self.public_perms(t)}
        shared: Shared = {}
        for t in self.types.values():
            for r in t.relations.values():
                for src in r.sources:
                    if src.kind == "shared":
                        subs = shared.setdefault(t.name, {}).setdefault(r.name, [])
                        for st, sr in src.subjects:
                            key = f"{st}:*" if sr == "*" else (f"{st}#{sr}" if sr else st)
                            if key not in subs:
                                subs.append(key)
        scopes = list(self.pol.scopes)
        return perms, shared, scopes

    def client(
        self,
        lang: str,
        source_name: str,
        java_class: str = JAVA_CLASS,
        elixir_module: str = ELIXIR_MODULE,
        mirror_columns: Mapping[str, list[str]] | None = None,
    ) -> str:
        """The client in `lang`; for java, the class `java_class` (its package, then its name: a.b.AuthzNames); for
        elixir, the module `elixir_module` (MyApp.Authz); for powersync, each mirror's columns as the database has
        them (mirror_columns: a synced table -> its mirror's columns, but readers)."""
        perms, shared, scopes = self._client_model()
        if lang == "java":
            return _client_java(perms, java_class, source_name)
        if lang == "elixir":
            return _client_elixir(perms, shared, scopes, elixir_module, source_name)
        if lang == "php":
            return _client_php(perms, source_name)
        if lang == "ts":
            return self._client_ts(perms, shared, scopes, source_name)
        if lang == "ts-sdk":  # rowstile.toml's ts, for an app on the TypeScript SDK
            return self._client_ts_names(perms, shared, scopes, source_name)
        if lang == "go":
            return self._client_go(perms, source_name)
        if lang == "rust":
            return _client_rust(perms, source_name)
        if lang == "csharp":
            return self._client_csharp(perms, source_name)
        if lang == "electric":
            return self._client_electric(source_name)
        if lang == "zero":
            return self._client_zero(source_name)
        if lang == "powersync":
            return self._client_powersync(source_name, mirror_columns or {})
        if lang in ("ruby", "rbs"):  # the names for the Ruby SDK, and their signatures, which Steep reads
            return _client_ruby(perms, shared, scopes, source_name, lang == "rbs")
        assert lang == "py", f"unknown client language '{lang}'"
        return self._client_py(perms, shared, scopes, source_name)

    def _client_ts(self, perms: Perms, shared: Shared, scopes: list[str], source_name: str) -> str:
        j: Callable[[object], str] = lambda x: json.dumps(x, indent=2)
        return f"""// Generated by rowstile client from {source_name}. Do not edit; re-run after changing the policy.
export const permissions = {j(perms)} as const;
export type ObjectType = keyof typeof permissions;
export type Permission<T extends ObjectType> = (typeof permissions)[T][number];

/** Relations people may share with authz.share(), and with whom (subject type, or type#relation). */
export const sharedRelations = {j(shared)} as const;
export type SharedType = keyof typeof sharedRelations;
export type SharedRelation<T extends SharedType> = keyof (typeof sharedRelations)[T] & string;

export const scopes = {j(scopes)} as const;
export type Scope = (typeof scopes)[number];

/** Anything with query(text, params) -> {{ rows }}: a pg Client, PoolClient, or similar. */
export interface Queryable {{
  query(text: string, params?: unknown[]): Promise<{{ rows: any[] }}>;
}}
/** An object's id; for a composite key, its columns in order: [orgId, id]. */
export type Id = string | number | bigint | readonly (string | number | bigint)[];
// an id as the database compares it: a composite key as Postgres reads a row (every field quoted, quotes and
// backslashes escaped, null as nothing); a key of one column given as an array is that value
const s = (id: Id): string => !Array.isArray(id) ? String(id) : id.length === 1 ? String(id[0])
  : "(" + id.map((v) => v == null ? "" : '"' + String(v).replace(/["\\\\]/g, (c) => "\\\\" + c) + '"').join(",") + ")";

/** A key as the database writes it, for a message: 7, or (1,2) for a key of several columns. A field is quoted
 *  as Postgres quotes it: when it is empty or holds a quote, a comma, a backslash, a parenthesis or one of
 *  ASCII's six spaces (a no-break space is not quoted); null is nothing. */
const shown = (id: Id): string => !Array.isArray(id) ? String(id) : id.length === 1 ? String(id[0])
  : "(" + id.map((v) => v == null ? "" : /^$|[",\\\\() \\t\\n\\r\\v\\f]/.test(String(v))
    ? '"' + String(v).replace(/\\\\/g, "\\\\\\\\").replace(/"/g, '""') + '"' : String(v)).join(",") + ")";
// who is signed in, in the words the database's own refusals use
const WHO = "SELECT coalesce((SELECT p.principal_type || ' ' || p.principal_id FROM authz.principal() p), 'someone not signed in') AS who";

/** The database refused a write (SQLSTATE 42501): its message, the table and command, and why (lines). */
export class Refused extends Error {{
  constructor(message: string, public table?: string, public command?: string, public why: string[] = []) {{ super(message); }}
}}
/** The row isn't there, or the signed-in user can't see it. */
export class NotFound extends Error {{
  constructor(public table: string, public id: string) {{ super(`${{table}} ${{id}} not found`); }}
}}
/** A Refused for a database error that is a refusal (from pg: code, detail, schema, table, constraint), else null. */
export function refusal(e: any): Refused | null {{
  if (!e || e.code !== "42501") return null;
  const constraint = String(e.constraint ?? "");
  return new Refused(String(e.message), e.schema && e.table ? `${{e.schema}}.${{e.table}}` : e.table,
    constraint.startsWith("authz_") ? constraint.slice(6) : undefined, e.detail ? String(e.detail).split("\\n") : []);
}}

/** Runs fn in a transaction signed in as userId (authz.act_as); rows are filtered by RLS. */
export async function asUser<R>(db: Queryable, userId: Id | null, fn: (db: Queryable) => Promise<R>): Promise<R> {{
  await db.query("BEGIN");
  try {{
    await db.query("SELECT authz.act_as('user', $1)", [userId === null ? null : s(userId)]);
    const out = await fn(db);
    await db.query("COMMIT");
    return out;
  }} catch (e) {{
    await db.query("ROLLBACK");
    throw e;
  }}
}}

/** The same for a principal other than a user (a service). */
export async function asPrincipal<R>(db: Queryable, principalType: string, id: Id, fn: (db: Queryable) => Promise<R>): Promise<R> {{
  await db.query("BEGIN");
  try {{
    await db.query("SELECT authz.act_as($1, $2)", [principalType, s(id)]);
    const out = await fn(db);
    await db.query("COMMIT");
    return out;
  }} catch (e) {{
    await db.query("ROLLBACK");
    throw e;
  }}
}}

/** Typed wrappers for the authz.* SQL API; call them inside asUser (or after authz.login_key/login_jwt). */
export function authz(db: Queryable) {{
  return {{
    can: async <T extends ObjectType>(type: T, id: Id, perm: Permission<T>): Promise<boolean> =>
      (await db.query("SELECT authz.can($1, $2::text, $3) AS ok", [type, s(id), perm])).rows[0].ok,
    /** What is wrong with this connection: call it when the app starts, and refuse to start on an 'error'. */
    connectionCheck: async (): Promise<{{ severity: string; problem: string }}[]> =>
      (await db.query("SELECT severity, problem FROM authz.connection_check()", [])).rows,
    /** Every id the user holds perm on; with limit, a page in key order after `after`. */
    list: async <T extends ObjectType>(type: T, perm: Permission<T>, page: {{ after?: Id; limit?: number }} = {{}}): Promise<string[]> =>
      (await db.query("SELECT x FROM authz.list($1, $2, $3, $4) x",
        [type, perm, page.after === undefined ? null : s(page.after), page.limit ?? null])).rows.map((r) => r.x),
    perms: async <T extends ObjectType>(type: T, id: Id): Promise<Permission<T>[]> =>
      (await db.query("SELECT authz.perms($1, $2::text) AS p", [type, s(id)])).rows[0].p ?? [],
    who: async <T extends ObjectType>(type: T, id: Id, perm: Permission<T>): Promise<string[]> =>
      (await db.query("SELECT x FROM authz.who($1, $2::text, $3) x", [type, s(id), perm])).rows.map((r) => r.x),
    explain: async <T extends ObjectType>(type: T, id: Id, perm: Permission<T>, user?: Id): Promise<string[]> =>
      (await db.query("SELECT e FROM authz.explain($1, $2::text, $3, $4) e", [type, s(id), perm, user === undefined ? null : s(user)])).rows.map((r) => r.e),
    share: async <T extends SharedType>(type: T, id: Id, relation: SharedRelation<T>, subjectType: string, subjectId: Id,
                                        opts: {{ subjectRelation?: string; expiresAt?: Date; startsAt?: Date; caveat?: string; caveatArgs?: object }} = {{}}) =>
      db.query("SELECT authz.share($1, $2::text, $3, $4, $5::text, $6, $7, $8, $9, $10)",
        [type, s(id), relation, subjectType, s(subjectId), opts.subjectRelation ?? "", opts.expiresAt ?? null, opts.startsAt ?? null,
         opts.caveat ?? null, opts.caveatArgs ? JSON.stringify(opts.caveatArgs) : null]),
    unshare: async <T extends SharedType>(type: T, id: Id, relation: SharedRelation<T>, subjectType: string, subjectId: Id, subjectRelation = "") =>
      db.query("SELECT authz.unshare($1, $2::text, $3, $4, $5::text, $6)", [type, s(id), relation, subjectType, s(subjectId), subjectRelation]),
    requestAccess: async <T extends SharedType>(type: T, id: Id, relation: SharedRelation<T>, reason: string, duration?: string): Promise<string> =>
      (await db.query("SELECT authz.request_access($1, $2::text, $3, $4, $5::interval) AS id", [type, s(id), relation, reason, duration ?? null])).rows[0].id,
    decideRequest: async (requestId: Id, approve: boolean, note?: string) =>
      db.query("SELECT authz.decide_request($1::bigint, $2, $3)", [s(requestId), approve, note ?? null]),
    /** A share with anyone holding the returned token (shown once; only its hash is stored). */
    createLink: async <T extends SharedType>(type: T, id: Id, relation: SharedRelation<T>, expiresAt?: Date): Promise<string> =>
      (await db.query("SELECT authz.create_link($1, $2::text, $3, $4) AS token", [type, s(id), relation, expiresAt ?? null])).rows[0].token,
    /** The links on an object (id, relation, created_by, created_at, expires_at), for those who can share it or may
     *  make such links. */
    listLinks: async <T extends ObjectType>(type: T, id: Id): Promise<any[]> =>
      (await db.query("SELECT * FROM authz.list_links($1, $2::text)", [type, s(id)])).rows,
    /** Turns a link off, by its id in listLinks (not its token). */
    revokeLink: async <T extends ObjectType>(type: T, id: Id, linkId: string) =>
      db.query("SELECT authz.revoke_link($1, $2::text, $3)", [type, s(id), linkId]),
    /** Link tokens the request presents, for this transaction. */
    useLinks: async (tokens: string[]) => db.query("SELECT set_config('authz_ctx.links', $1, true)", [tokens.join(",")]),
    cancelRequest: async (requestId: Id) => db.query("SELECT authz.cancel_request($1::bigint)", [s(requestId)]),
    pendingRequests: async (): Promise<any[]> => (await db.query("SELECT * FROM authz.pending_requests()")).rows,
    listShares: async <T extends ObjectType>(type: T, id: Id): Promise<any[]> =>
      (await db.query("SELECT * FROM authz.list_shares($1, $2::text)", [type, s(id)])).rows,
    breakGlass: async <T extends SharedType>(type: T, id: Id, relation: SharedRelation<T>, reason: string, duration = "1 hour") =>
      db.query("SELECT authz.break_glass($1, $2::text, $3, $4, $5::interval)", [type, s(id), relation, reason, duration]),
    startReview: async <T extends ObjectType>(type: T, id: Id, closesAt?: Date): Promise<string> =>
      (await db.query("SELECT authz.start_review($1, $2::text, coalesce($3::timestamptz, now() + interval '14 days')) AS id",
        [type, s(id), closesAt ?? null])).rows[0].id,
    reviewItems: async (reviewId: Id): Promise<any[]> => (await db.query("SELECT * FROM authz.review_items($1::bigint)", [s(reviewId)])).rows,
    reviewDecide: async (reviewId: Id, item: number, keep: boolean) =>
      db.query("SELECT authz.review_decide($1::bigint, $2, $3)", [s(reviewId), item, keep]),
    closeReview: async (reviewId: Id, revokeUndecided = false): Promise<number> =>
      (await db.query("SELECT authz.close_review($1::bigint, $2) AS n", [s(reviewId), revokeUndecided])).rows[0].n,
    loginKey: async (key: string) => db.query("SELECT authz.login_key($1)", [key]),
    loginJwt: async (token: string) => db.query("SELECT authz.login_jwt($1)", [token]),
    /** A key for yourself, or (holding manage_keys on it) for a principal such as a service. Shown once. */
    createApiKey: async (name: string, opts: {{ scopes?: string; expiresAt?: Date; principalType?: string; principalId?: Id }} = {{}}): Promise<string> =>
      (await db.query("SELECT authz.create_api_key($1, $2, $3, $4, $5) AS key",
        [name, opts.scopes ?? "", opts.expiresAt ?? null, opts.principalType ?? null,
         opts.principalId === undefined ? null : s(opts.principalId)])).rows[0].key,
    listApiKeys: async (principalType?: string, principalId?: Id): Promise<any[]> =>
      (await db.query("SELECT * FROM authz.list_api_keys($1, $2)", [principalType ?? null, principalId === undefined ? null : s(principalId)])).rows,
    revokeApiKey: async (keyId: Id) => db.query("SELECT authz.revoke_api_key($1::bigint)", [s(keyId)]),
    /** Why a write is or would be refused: an insert (row: the new row), or an update or delete of the row with this
     *  id (for an update, row: the new values). null: that row isn't there, or you can't see it. */
    explainRule: async (table: string, command: "insert" | "update" | "delete", id?: Id, row?: object): Promise<string[] | null> =>
      (await db.query("SELECT authz.explain_rule($1, $2, $3, $4::jsonb) AS e",
        [table, command, id === undefined ? null : s(id), row === undefined ? null : JSON.stringify(row)])).rows[0].e,
    /** The result of an UPDATE or DELETE (rows, a count, or what the driver gave: its rowCount or rows): returned
     *  if anything changed, otherwise NotFound (you can't see the row) or Refused (you may not, and why). */
    expect: async <R>(result: R, table: string, command: "update" | "delete", id: Id, row?: object): Promise<R> => {{
      const given: any = result;
      const changed = Array.isArray(given) ? given.length > 0 : typeof given === "number" ? given > 0
        : given && typeof given.rowCount === "number" ? given.rowCount > 0
        : given && Array.isArray(given.rows) ? given.rows.length > 0 : Boolean(given);
      if (changed) return result;
      const why: string[] | null = (await db.query("SELECT authz.explain_rule($1, $2, $3, $4::jsonb) AS e",
        [table, command, s(id), row === undefined ? null : JSON.stringify(row)])).rows[0].e;
      // nothing there for this user, or the rule allows it (its first line says yes) and the statement matched
      // nothing for another reason, such as a WHERE with more than the key
      if (why === null || /^\\s*yes\\b/.test(why[0] ?? "")) throw new NotFound(table, shown(id));
      const who: string = (await db.query(WHO)).rows[0].who;
      throw new Refused(`permission denied: ${{who}} may not ${{command}} row ${{shown(id)}} of ${{table}}`, table, command, why);
    }},
    /** Which of these people (or principals of another type) hold perm: one call, for live updates. Signs each one
     *  in, so it needs what signing in needs (SET on authz.user_id). */
    whoAmong: async <T extends ObjectType>(type: T, id: Id, perm: Permission<T>, principals: Id[], principalType = "user"): Promise<string[]> =>
      (await db.query("SELECT x FROM authz.who_among($1, $2::text, $3, $4::text[], $5) x",
        [type, s(id), perm, principals.map(s), principalType])).rows.map((r) => r.x),
  }};
}}
"""

    def electric_shapes(self) -> dict[str, dict[str, object]]:
        """Electric's shape of each synced table (a preview): its table, its key columns, the columns the policy
        masks, and for each principal type the filter: the rows whose readers hold a key the signed-in principal
        holds, its id the parameter $1 (the sync index's join, as Electric's where takes it: sync_filter_sql)."""
        out: dict[str, dict[str, object]] = {}
        for s in self.pol.syncs.values():
            t = self.sync_type(s)
            keys = [c for c, _ in t.key]
            masked = [c for r in self.rules if r.table == s.table and r.command == "mask" for c in r.columns]
            out[s.table] = {
                "table": s.table,
                "keys": keys,
                "masked": masked,
                "where": {p.name: self.sync_filter_sql(t, p, "$1") for p in self.sync_principals()},
            }
        return out

    def _client_electric(self, source_name: str) -> str:
        """For an app's proxy in front of Electric (a preview): each synced table's shape, as constants. Only the
        policy's names and the filter's text: the proxy sets them server-side, whatever the client sends."""
        j: Callable[[object], str] = lambda x: json.dumps(x, indent=2)
        return f"""// Generated by rowstile client from {source_name}. Do not edit; re-run after changing the policy.
// Electric's shapes of the tables the policy syncs (a preview), for the app's proxy, which sets them server-side
// whatever the client sends: the rows whose readers hold a key the signed-in principal holds (where, by the
// principal's type; $1 is its id), the key columns always, and never a column the policy masks.
export const shapes = {j(self.electric_shapes())} as const;
export type SyncedTable = keyof typeof shapes;
"""

    def _client_powersync(self, source_name: str, columns: Mapping[str, list[str]]) -> str:
        """For PowerSync's service (a preview): a stream of each mirrored table, its rows in the bucket of each key
        that may read them, for the principal the token names (its sub, and principal_type: user if it says none);
        the mirror's columns but readers (which would tell a client who else reads the row). A stream's alias is the
        table's name on the client: the table's own, which no two mirrored tables share (AZ811), quoted (`order`)."""
        streams = []
        for s, t in self.mirrored():
            name = s.table.split(".")[-1]
            cols = columns.get(s.table)
            assert cols, f"{s.table}'s mirror: its columns, from the database (database.mirror_columns)"
            alias = q(name)
            listed = ", ".join(f"{alias}.{q(c)}" for c in cols)
            streams.append(
                f"""  {name}:
    auto_subscribe: true
    query: |
      SELECT {listed}
      FROM authz_sync.{q(t.name + "__mirror")} {alias}, json_each({alias}.readers) r
      WHERE r.value IN (SELECT key FROM authz_sync.keys
                        WHERE principal_type = ifnull(auth.parameter('principal_type'), 'user')
                          AND principal_id = auth.user_id())"""
            )
        body = "\n".join(streams) if streams else "  {}"
        return f"""# Generated by rowstile client from {source_name}. Do not edit; re-run after changing the policy or a mirrored table.
# PowerSync's streams of the tables the policy mirrors (a preview), for the service's sync config: each row of a
# mirror in the bucket of each key that may read it (a bucket for each key the principal holds), for the principal
# the token names: its sub, and the claim principal_type (user if it has none). Never readers, nor a column the
# policy masks (the mirror has none). The service reads the publication powersync: the mirrors and authz_sync.keys.
config:
  edition: 3
streams:
{body}
"""

    def _client_zero(self, source_name: str) -> str:
        """For an app on Zero (a preview): the sync index's tables as Zero tables, with the relationships between
        them; the relationship each synced table needs to its readers; the columns the policy masks; and each synced
        table's filter, for the app's query endpoint (the ZQL zero-cache runs): the rows whose readers hold a key the
        signed-in principal holds, as sync_filter_sql says, written with whereExists. Only the policy's names."""
        st = self.sync_build()
        lines = [(s, self.sync_type(s)) for s in self.pol.syncs.values()]
        keyed = [s.table for s, _ in lines if s.by is not None and st.keyed]
        j: Callable[[object], str] = lambda x: json.dumps(x)

        def column(pgtype: str) -> str:
            # a key column as Zero types it: its numbers are JavaScript numbers, its booleans booleans, the rest text
            numbers = ("smallint", "integer", "int", "int2", "int4", "bigint", "int8", "real", "double precision")
            return "number()" if pgtype in numbers else "boolean()" if pgtype == "boolean" else "string()"

        def camel(t: Type) -> str:  # org_unit: orgUnitReaders
            return re.sub(r"_(\w)", lambda m: m.group(1).upper(), t.name) + "Readers"

        spelled: dict[str, int] = {}
        for _, t in lines:
            spelled[camel(t)] = spelled.get(camel(t), 0) + 1

        def var(t: Type) -> str:
            """The constant of a type's readers table: its name in camelCase, or as written where two types would
            have one (a_b and aB), which no name in camelCase is (a name holds no `__`, nor ends with `_`)."""
            return camel(t) if spelled[camel(t)] == 1 else t.name + "Readers"

        tables = [
            'const keys = table("rowstile_keys").from("authz_sync.keys")\n'
            "  .columns({principal_type: string(), principal_id: string(), key: string()})\n"
            '  .primaryKey("principal_type", "principal_id", "key");'
        ]
        if keyed:
            tables.append(
                'const inherits = table("rowstile_inherits").from("authz_sync.inherits")\n'
                '  .columns({key: string(), source: string()}).primaryKey("key", "source");\n'
                'const given = table("rowstile_given").from("authz_sync.given")\n'
                '  .columns({source: string(), key: string()}).primaryKey("source", "key");'
            )
        rels = []
        for s, t in lines:
            cols = ", ".join(f"{c}: {column(ty)}" for c, ty in t.key)
            pk = ", ".join(j(c) for c, _ in t.key)
            tables.append(
                f"const {var(t)} = table({j('rowstile_' + t.name + '_readers')}).from("
                f'{j("authz_sync." + t.name + "__readers")})\n  .columns({{{cols}, key: string()}}).primaryKey({pk}, "key");'
            )
            through = (
                ',\n    inherits: many({sourceField: ["key"], destField: ["key"], destSchema: inherits})'
                if s.table in keyed
                else ""
            )
            rels.append(
                f"  relationships({var(t)}, ({{many}}) => ({{\n"
                f'    holders: many({{sourceField: ["key"], destField: ["key"], destSchema: keys}}){through},\n  }})),'
            )
        if keyed:
            rels.append(
                "  relationships(inherits, ({many}) => ({\n"
                '    given: many({sourceField: ["source"], destField: ["source"], destSchema: given}),\n  })),\n'
                "  relationships(given, ({many}) => ({\n"
                '    holders: many({sourceField: ["key"], destField: ["key"], destSchema: keys}),\n  })),'
            )
        names = [var(t) for _, t in lines]
        readers = "\n".join(
            f"  {j(s.table)}: {{sourceField: [{', '.join(j(c) for c, _ in t.key)}], destField: "
            f"[{', '.join(j(c) for c, _ in t.key)}], destSchema: {var(t)}}},"
            for s, t in lines
        )
        masked = {
            s.table: [c for r in self.rules if r.table == s.table and r.command == "mask" for c in r.columns]
            for s, _ in lines
        }
        held = 'k.where("principal_type", by.type).where("principal_id", by.id)'
        filters = []
        for s, _ in lines:
            if s.table in keyed:
                body = (
                    'q.whereExists("readers", (r: Sub) => r.where(({or, exists}: Sub) => or(\n'
                    f'      exists("holders", (k: Sub) => {held}),\n'
                    '      exists("inherits", (i: Sub) => i.whereExists("given", (g: Sub) =>\n'
                    f'        g.whereExists("holders", (k: Sub) => {held})))))),'
                )
            else:
                body = f'q.whereExists("readers", (r: Sub) => r.whereExists("holders", (k: Sub) => {held})),'
            filters.append(f"  {j(s.table)}: <Q extends Zql<Q>>(q: Q, by: SyncedBy): Q =>\n    {body}")
        principals = " | ".join(j(p.name) for p in self.sync_principals()) or "never"
        builders = {column(ty) for _, t in lines for _, ty in t.key}
        imports = ", ".join(
            [
                *(["boolean"] if "boolean()" in builders else []),
                *(["number"] if "number()" in builders else []),
                *(["relationships"] if lines else []),
                "string",
                "table",
            ]
        )
        nl = "\n"
        return f"""// Generated by rowstile client from {source_name}. Do not edit; re-run after changing the policy.
// Zero's view of the sync index (a preview), for the app's Zero schema and its query endpoint: the index's tables
// and their relationships (syncTables, syncRelationships: add them to createSchema), the relationship each synced
// table needs to its readers (readers: `readers: many(readers["app.files"])` in the table's own relationships),
// the columns the policy masks (never in the app's Zero tables, nor in the publication), and each table's filter
// (readable), which the query endpoint adds to the ZQL it returns: the rows whose readers hold a key the signed-in
// principal holds. The client syncs the rows the filter reads too: only its own keys, and readers of those.
import {{ {imports} }} from "@rocicorp/zero";

{nl.join(tables)}

export const syncTables = [{", ".join(["keys", *names, *(["inherits", "given"] if keyed else [])])}] as const;
export const syncRelationships = {"[]" if not rels else "[" + nl + nl.join(rels) + nl + "]"} as const;

/** The relationship a synced table needs to its readers, named `readers` in its own relationships. */
export const readers = {"{}" if not readers else "{" + nl + readers + nl + "}"} as const;

/** The columns the policy masks: never in the app's Zero table, nor in the publication zero-cache reads. */
export const masked = {j(masked)} as const;

/** Whom a filter is for: a principal type the policy signs in, and its id (syncPrincipal, from @rowstile/client). */
export interface SyncedBy {{
  readonly type: {principals};
  readonly id: string;
}}

/** The part of ZQL the filters use: whereExists on the synced table's query, and on its relationships' */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type Sub = any;
interface Zql<Q> {{
  whereExists(relationship: string, cb: (q: Sub) => Sub): Q;
}}

/** Each synced table's filter: add it to the ZQL the query endpoint returns for that table. */
export const readable = {"{}" if not filters else "{" + nl + nl.join(filters) + nl + "}"} as const;
export type SyncedTable = keyof typeof readable;
"""

    def _client_ts_names(self, perms: Perms, shared: Shared, scopes: list[str], source_name: str) -> str:
        """For apps on the TypeScript SDK (@rowstile/*): only the policy's names, registered with the SDK, so
        its functions take only the types and permissions the policy declares."""
        j: Callable[[object], str] = lambda x: json.dumps(x, indent=2)
        return f"""// Generated by rowstile client from {source_name}. Do not edit; re-run after changing the policy.
// The policy's names, for the SDK (@rowstile/client): a misspelled type or permission doesn't type-check.
import type {{}} from "@rowstile/client";

export const permissions = {j(perms)} as const;
export type ObjectType = keyof typeof permissions;
export type Permission<T extends ObjectType> = (typeof permissions)[T][number];

/** Relations people may share, and with whom (subject type, or type#relation). */
export const sharedRelations = {j(shared)} as const;

export const scopes = {j(scopes)} as const;
export type Scope = (typeof scopes)[number];

declare module "@rowstile/client" {{
  interface Register {{
    permissions: typeof permissions;
    sharedRelations: typeof sharedRelations;
  }}
}}
"""

    def _client_go(self, perms: Perms, source_name: str) -> str:
        """For apps on the Go SDK (github.com/rowstile/rowstile/sdk/go): the policy's types, and each type's
        permissions as a type of their own, which the SDK's calls take. A misspelled name doesn't build, and
        neither does a plain string where the SDK wants a permission. Names in Go's spelling: note's edit is
        NoteEdit, of the type NotePermission; two names that would be spelled the same get neither, and neither does
        one that would be ObjectType (object's type), the file's own."""

        def go(*parts: str) -> str:  # org_unit and orgUnit: OrgUnit
            return "".join(w[:1].upper() + w[1:] for p in parts for w in p.split("_"))

        names: dict[str, list[str]] = {}  # a Go name: what it would stand for
        for t, ps in perms.items():
            names.setdefault("Type" + go(t), []).append(t)
            names.setdefault(go(t) + "Permission", []).append(t)
            for p in ps:
                names.setdefault(go(t, p), []).append(f"{t}.{p}")
        names.setdefault("ObjectType", []).insert(0, "the file's ObjectType")
        unique: Callable[[str], bool] = lambda name: len(names[name]) == 1
        q: Callable[[str], str] = lambda s: json.dumps(s)
        out = [
            f"// Code generated by rowstile client from {source_name}. DO NOT EDIT.",
            "",
            "// Package authz holds the policy's names for the rowstile SDK (github.com/rowstile/rowstile/sdk/go): its",
            "// types, and each type's permissions as a type of their own. A misspelled name doesn't build, and",
            "// neither does a plain string where the SDK takes a permission.",
            "package authz",
            "",
            "// ObjectType is a type the policy declares.",
            "type ObjectType string",
        ]
        for t, ps in perms.items():
            if not unique("Type" + go(t)):
                if names["Type" + go(t)][0] == t:
                    out += ["", f"// {' and '.join(names['Type' + go(t)])} would both be Type{go(t)}: neither has it"]
            else:
                out += ["", f"// Type{go(t)} is the type {t}.", f"const Type{go(t)} ObjectType = {q(t)}"]
            kind = go(t) + "Permission"
            if not unique(kind):
                if names[kind][0] == t:
                    out += ["", f"// {' and '.join(names[kind])} would both be {kind}: neither has it"]
                continue
            out += [
                "",
                f"// {kind} is a permission of {t}.",
                f"type {kind} string",
                "",
                f"// ObjectType is {t}, the type {kind} is a permission of.",
                f"func ({kind}) ObjectType() string {{ return {q(t)} }}",
            ]
            for p in ps:
                name = go(t, p)
                if unique(name):
                    out += ["", f"// {name} is {t}'s permission {p}.", f"const {name} {kind} = {q(p)}"]
                elif names[name][0] == f"{t}.{p}":
                    out += ["", f"// {' and '.join(names[name])} would both be {name}: neither has it"]
                elif name == "ObjectType":
                    out += ["", f"// {t}.{p} would be ObjectType, the file's own: it has no name"]
        return "\n".join(out) + "\n"

    def _client_csharp(self, perms: Perms, source_name: str) -> str:
        """For .NET apps on the SDK (Rowstile): the policy's names as C#, a class for each type holding its
        ObjectType and its Permissions (Policy.Note.Edit), so a misspelled one doesn't compile. A name is the
        policy's in PascalCase (org_unit: OrgUnit); one that would clash (with another, the class around it, a
        member a class has already, one every class inherits from object, which it would hide, or the SDK's
        ObjectType and Permission, which a class of that name would hide in Policy) has none, and says so."""

        # what every class inherits from object: a member of that name hides it, a warning (CS0108)
        inherited = {"Equals", "ReferenceEquals", "ToString", "GetHashCode", "GetType", "MemberwiseClone"}

        def pascal(name: str) -> str:
            return "".join(part[:1].upper() + part[1:] for part in name.split("_"))

        def named(names: list[str], taken: set[str]) -> tuple[dict[str, str], list[str]]:
            """{policy name: C# name}, and the lines that say which have none."""
            by: dict[str, list[str]] = {}
            for n in names:
                by.setdefault(pascal(n), []).append(n)
            out: dict[str, str] = {}
            said: list[str] = []
            for cs, ns in by.items():
                if len(ns) == 1 and cs and cs not in taken:
                    out[ns[0]] = cs
                else:
                    which = " and ".join(ns)
                    said.append(
                        f"// {which} would {'both ' if len(ns) > 1 else ''}be {cs or 'no name'}: "
                        f"{'neither has' if len(ns) > 1 else 'it has no'} name here, use new Permission(...)"
                    )
            return out, said

        types, said = named(list(perms), {"Policy", "ObjectType", "Permission", *inherited})
        lines = [
            "// <auto-generated />",
            f"// Generated by rowstile client from {source_name}. Do not edit; re-run after changing the policy.",
            "// The policy's names, for the SDK (Rowstile): a misspelled type or permission doesn't compile.",
            "#nullable enable",
            "using Rowstile;",
            "",
            "namespace Rowstile.Generated;",
            "",
            "/// <summary>The policy's types, each with its permissions: <c>Policy.Note.Edit</c>.</summary>",
            "public static class Policy",
            "{",
            *(f"    {x}" for x in said),
        ]
        for t, cls in types.items():
            members, unnamed = named(perms[t], {"Type", cls, *inherited})
            lines += [
                f"    /// <summary>{t}: {', '.join(perms[t])}.</summary>",
                f"    public static class {cls}",
                "    {",
                f"        /// <summary>{t}, as the policy names it.</summary>",
                f"        public static readonly ObjectType Type = new({json.dumps(t)});",
                *(f"        {x}" for x in unnamed),
            ]
            for p, member in members.items():
                lines += [
                    f"        /// <summary>{t}'s {p}.</summary>",
                    f"        public static readonly Permission {member} = new(Type, {json.dumps(p)});",
                ]
            lines.append("    }")
        return "\n".join([*lines, "}", ""])

    def _client_py(self, perms: Perms, shared: Shared, scopes: list[str], source_name: str) -> str:
        lit_union: Callable[[list[str]], str] = lambda xs: (
            "Literal[" + ", ".join(json.dumps(x) for x in xs) + "]" if xs else "str"
        )
        all_perms = sorted({p for ps in perms.values() for p in ps})
        # each type's own: its name with a capital first letter, the rest as written (orgUnit: OrgUnitPermission)
        alias: Callable[[str], str] = lambda t: t[:1].upper() + t[1:] + "Permission"
        named: dict[str, list[str]] = {}
        for t in perms:
            named.setdefault(alias(t), []).append(t)
        per_type = "\n".join(
            f"{alias(t)} = {lit_union(ps)}"
            if len(named[alias(t)]) == 1
            else f"# {' and '.join(named[alias(t)])} would both be {alias(t)}: neither has it, use Permission"
            for t, ps in perms.items()
            if named[alias(t)][0] == t
        )
        return f'''"""Generated by rowstile client from {source_name}. Do not edit; re-run after changing the policy.

Works with any DB-API connection using %s placeholders (psycopg, psycopg2):

    with conn.transaction():                     # psycopg 3; or: BEGIN ... COMMIT
        Authz(conn).sign_in(7)                   # SELECT authz.act_as('user', '7')
        if Authz(conn).can("file", 11, "edit"): ...
"""
from __future__ import annotations

import datetime
import json
import uuid
from collections.abc import Sequence
from types import TracebackType
from typing import TYPE_CHECKING, Literal, Protocol, TypeVar

if TYPE_CHECKING:
    from typing import LiteralString  # Python 3.11

PERMISSIONS: dict[str, list[str]] = {json.dumps(perms, indent=4)}
SHARED_RELATIONS: dict[str, dict[str, list[str]]] = {json.dumps(shared, indent=4)}
SCOPES: list[str] = {json.dumps(scopes)}

ObjectType = {lit_union(list(perms))}
Permission = {lit_union(all_perms)}
{per_type}
# an object's id; for a composite key, its columns in order: (org_id, id)
Id = int | str | uuid.UUID | tuple[int | str | uuid.UUID, ...]
When = datetime.datetime | str                  # a timestamptz: a datetime, or text Postgres reads
Row = dict[str, object]
Result = TypeVar("Result")


class Cursor(Protocol):
    """What the client uses of a DB-API cursor (psycopg's, psycopg2's)."""
    @property
    def description(self) -> Sequence[Sequence[object]] | None: ...
    def execute(self, query: LiteralString, params: Sequence[object], /) -> object: ...
    def fetchone(self) -> Sequence[object] | None: ...
    def fetchall(self) -> Sequence[Sequence[object]]: ...
    def __enter__(self) -> Cursor: ...
    def __exit__(self, exc_type: type[BaseException] | None, exc: BaseException | None,
                 tb: TracebackType | None, /) -> object: ...


class Connection(Protocol):
    def cursor(self) -> Cursor: ...


def _texts(value: object) -> list[str]:
    """A text[] from the database (None: none)."""
    return [str(x) for x in value] if isinstance(value, (list, tuple)) else []


def _int(value: object) -> int:
    if isinstance(value, (int, str)):
        return int(value)
    raise TypeError(f"expected a number from the database, got {{value!r}}")


def _id(x: Id) -> str:
    """An id as the database compares it: a composite key as Postgres reads a row (every field quoted, quotes and
    backslashes escaped, None as nothing); a key of one column given as a tuple is that value."""
    if not isinstance(x, (tuple, list)):
        return str(x)
    if len(x) == 1:
        return str(x[0])
    return "(" + ",".join("" if v is None else '"' + str(v).replace("\\\\", "\\\\\\\\").replace('"', '\\\\"') + '"' for v in x) + ")"


def _shown(x: Id) -> str:
    """A key as the database writes it, for a message: 7, or (1,2) for a key of several columns. A field is quoted
    as Postgres quotes it: when it is empty or holds a quote, a comma, a backslash, a parenthesis or one of ASCII's
    six spaces (a no-break space is not quoted); None is nothing."""
    if not isinstance(x, (tuple, list)):
        return str(x)
    if len(x) == 1:
        return str(x[0])

    def field(v: object) -> str:
        if v is None:
            return ""
        s = str(v)
        if s == "" or any(ch in s for ch in '",\\\\() \\t\\n\\r\\v\\f'):
            return '"' + s.replace("\\\\", "\\\\\\\\").replace('"', '""') + '"'
        return s

    return "(" + ",".join(field(v) for v in x) + ")"


# who is signed in, in the words the database's own refusals use
_WHO = "SELECT coalesce((SELECT p.principal_type || ' ' || p.principal_id FROM authz.principal() p), 'someone not signed in')"


class Refused(Exception):
    """The database refused a write (SQLSTATE 42501): its message, the table and command, and why (lines)."""

    def __init__(self, message: str, table: str | None = None, command: str | None = None, why: Sequence[str] = ()) -> None:
        super().__init__(message)
        self.message, self.table, self.command, self.why = message, table, command, list(why)


class NotFound(Exception):
    """The row isn't there, or the signed-in user can't see it."""

    def __init__(self, table: str, id_: str) -> None:
        super().__init__(f"{{table}} {{id_}} not found")
        self.table, self.id = table, id_


def refusal(error: BaseException) -> Refused | None:
    """A Refused for a database error that is a refusal, else None (psycopg, psycopg2)."""
    if (getattr(error, "sqlstate", None) or getattr(error, "pgcode", None)) != "42501":
        return None
    diag = getattr(error, "diag", None)
    message = getattr(diag, "message_primary", None) or str(error).split("\\n")[0]
    detail = getattr(diag, "message_detail", None) or ""
    schema, table = getattr(diag, "schema_name", None), getattr(diag, "table_name", None)
    constraint = getattr(diag, "constraint_name", None) or ""
    return Refused(message, f"{{schema}}.{{table}}" if schema and table else table,
                   constraint[6:] if constraint.startswith("authz_") else None, detail.split("\\n") if detail else [])


class Authz:
    def __init__(self, conn: Connection) -> None:
        self.conn = conn

    def _one(self, sql: LiteralString, args: Sequence[object]) -> object:
        with self.conn.cursor() as cur:
            cur.execute(sql, args)
            row = cur.fetchone()
            return row[0] if row else None

    def _all(self, sql: LiteralString, args: Sequence[object]) -> Sequence[str]:
        with self.conn.cursor() as cur:
            cur.execute(sql, args)
            return [str(r[0]) for r in cur.fetchall()]

    def _rows(self, sql: LiteralString, args: Sequence[object]) -> Sequence[Row]:
        with self.conn.cursor() as cur:
            cur.execute(sql, args)
            names = [str(d[0]) for d in cur.description or []]
            return [dict(zip(names, r, strict=True)) for r in cur.fetchall()]

    @staticmethod
    def _check(type_: str, perm: str) -> None:
        if type_ not in PERMISSIONS or perm not in PERMISSIONS[type_]:
            raise ValueError(f"{{type_}} has no permission {{perm!r}} in the policy")

    def sign_in(self, user_id: Id | None) -> None:
        """For this transaction only (run inside a transaction); None: nobody. A signed session (authz.act_as)."""
        self._one("SELECT authz.act_as('user', %s)", (None if user_id is None else _id(user_id),))

    def sign_in_as(self, principal_type: str, principal_id: Id) -> None:
        """A principal other than a user (a service), for this transaction only."""
        self._one("SELECT authz.act_as(%s, %s)", (principal_type, _id(principal_id)))

    def connection_check(self) -> Sequence[Row]:
        """What is wrong with this connection, as rows of severity and problem: call it when the app starts, and
        refuse to start on an 'error' (a role row-level security doesn't apply to, or one the policy doesn't govern)."""
        return self._rows("SELECT severity, problem FROM authz.connection_check()", ())

    def principal(self) -> tuple[str, str] | None:
        """(type, id) of whoever is signed in, or None."""
        rows = self._all("SELECT principal_type || ':' || principal_id FROM authz.principal()", ())
        if not rows:
            return None
        kind, _, pid = rows[0].partition(":")
        return kind, pid

    def login_key(self, key: str) -> None:
        self._one("SELECT authz.login_key(%s)", (key,))

    def login_jwt(self, token: str) -> None:
        self._one("SELECT authz.login_jwt(%s)", (token,))

    def create_api_key(self, name: str, scopes: str = "", expires_at: When | None = None, principal_type: str | None = None,
                       principal_id: Id | None = None) -> str:
        """A key for yourself, or (holding manage_keys on it) for a principal such as a service. Shown once."""
        return str(self._one("SELECT authz.create_api_key(%s, %s, %s, %s, %s)",
                             (name, scopes, expires_at, principal_type, None if principal_id is None else _id(principal_id))))

    def list_api_keys(self, principal_type: str | None = None, principal_id: Id | None = None) -> Sequence[Row]:
        return self._rows("SELECT * FROM authz.list_api_keys(%s, %s)",
                          (principal_type, None if principal_id is None else _id(principal_id)))

    def revoke_api_key(self, key_id: int) -> None:
        self._one("SELECT authz.revoke_api_key(%s)", (key_id,))

    def can(self, type_: ObjectType, id_: Id, perm: Permission) -> bool:
        self._check(type_, perm)
        return bool(self._one("SELECT authz.can(%s, %s::text, %s)", (type_, _id(id_), perm)))

    def list(self, type_: ObjectType, perm: Permission, after: Id | None = None,
             limit: int | None = None) -> Sequence[str]:
        """Every id the user holds perm on; with limit, a page in key order after `after`."""
        self._check(type_, perm)
        return self._all("SELECT x FROM authz.list(%s, %s, %s, %s) x",
                         (type_, perm, None if after is None else _id(after), limit))

    def perms(self, type_: ObjectType, id_: Id) -> Sequence[str]:
        return _texts(self._one("SELECT authz.perms(%s, %s::text)", (type_, _id(id_))))

    def who(self, type_: ObjectType, id_: Id, perm: Permission) -> Sequence[str]:
        self._check(type_, perm)
        return self._all("SELECT x FROM authz.who(%s, %s::text, %s) x", (type_, _id(id_), perm))

    def explain(self, type_: ObjectType, id_: Id, perm: Permission, user: Id | None = None) -> Sequence[str]:
        return self._all("SELECT e FROM authz.explain(%s, %s::text, %s, %s) e",
                         (type_, _id(id_), perm, None if user is None else _id(user)))

    def share(self, type_: str, id_: Id, relation: str, subject_type: str, subject_id: Id, subject_relation: str = "",
              expires_at: When | None = None, starts_at: When | None = None, caveat: str | None = None,
              caveat_args: Row | None = None) -> None:
        """caveat_args: what the caveat's arg('name') reads, {{"ip": "10.0.0.7"}}."""
        if relation not in SHARED_RELATIONS.get(type_, {{}}):
            raise ValueError(f"{{type_}}.{{relation}} is not shared in the policy")
        self._one("SELECT authz.share(%s, %s::text, %s, %s, %s::text, %s, %s, %s, %s, %s::jsonb)",
                  (type_, _id(id_), relation, subject_type, _id(subject_id), subject_relation, expires_at, starts_at,
                   caveat, None if caveat_args is None else json.dumps(caveat_args, default=str)))

    def create_link(self, type_: str, id_: Id, relation: str, expires_at: When | None = None) -> str:
        """A share with anyone holding the returned token (shown once; only its hash is stored)."""
        if relation not in SHARED_RELATIONS.get(type_, {{}}):
            raise ValueError(f"{{type_}}.{{relation}} is not shared in the policy")
        return str(self._one("SELECT authz.create_link(%s, %s::text, %s, %s)", (type_, _id(id_), relation, expires_at)))

    def list_links(self, type_: ObjectType, id_: Id) -> Sequence[Row]:
        """The links on an object (id, relation, created_by, created_at, expires_at), for those who can share it
        or may make such links."""
        return self._rows("SELECT * FROM authz.list_links(%s, %s::text)", (type_, _id(id_)))

    def revoke_link(self, type_: ObjectType, id_: Id, link_id: str) -> None:
        """Turns a link off, by its id in list_links (not its token)."""
        self._one("SELECT authz.revoke_link(%s, %s::text, %s)", (type_, _id(id_), link_id))

    def use_links(self, tokens: Sequence[str]) -> None:
        """Link tokens the request presents, for this transaction (SET LOCAL authz_ctx.links)."""
        self._one("SELECT set_config('authz_ctx.links', %s, true)", (",".join(tokens),))

    def unshare(self, type_: str, id_: Id, relation: str, subject_type: str, subject_id: Id, subject_relation: str = "") -> None:
        self._one("SELECT authz.unshare(%s, %s::text, %s, %s, %s::text, %s)",
                  (type_, _id(id_), relation, subject_type, _id(subject_id), subject_relation))

    def request_access(self, type_: str, id_: Id, relation: str, reason: str, duration: str | None = None) -> int:
        return _int(self._one("SELECT authz.request_access(%s, %s::text, %s, %s, %s::interval)",
                              (type_, _id(id_), relation, reason, duration)))

    def decide_request(self, request_id: int, approve: bool, note: str | None = None) -> None:
        self._one("SELECT authz.decide_request(%s, %s, %s)", (request_id, approve, note))

    def cancel_request(self, request_id: int) -> None:
        self._one("SELECT authz.cancel_request(%s)", (request_id,))

    def pending_requests(self) -> Sequence[Row]:
        """Requests the user may decide, and their own (mine = true)."""
        return self._rows("SELECT * FROM authz.pending_requests()", ())

    def list_shares(self, type_: ObjectType, id_: Id) -> Sequence[Row]:
        """The shares on an object, for a sharing dialog."""
        return self._rows("SELECT * FROM authz.list_shares(%s, %s::text)", (type_, _id(id_)))

    def break_glass(self, type_: str, id_: Id, relation: str, reason: str, duration: str = "1 hour") -> None:
        self._one("SELECT authz.break_glass(%s, %s::text, %s, %s, %s::interval)", (type_, _id(id_), relation, reason, duration))

    def start_review(self, type_: ObjectType, id_: Id, closes_at: When | None = None) -> int:
        return _int(self._one("SELECT authz.start_review(%s, %s::text, coalesce(%s::timestamptz, now() + interval '14 days'))",
                              (type_, _id(id_), closes_at)))

    def review_items(self, review_id: int) -> Sequence[Row]:
        return self._rows("SELECT * FROM authz.review_items(%s)", (review_id,))

    def review_decide(self, review_id: int, item: int, keep: bool) -> None:
        self._one("SELECT authz.review_decide(%s, %s, %s)", (review_id, item, keep))

    def close_review(self, review_id: int, revoke_undecided: bool = False) -> int:
        return _int(self._one("SELECT authz.close_review(%s, %s)", (review_id, revoke_undecided)))

    def explain_rule(self, table: str, command: str, id_: Id | None = None, row: Row | None = None) -> Sequence[str] | None:
        """Why a write is or would be refused: an insert (row: the new row), or an update or delete of the row with
        this id (for an update, row: the new values). None: that row isn't there, or you can't see it."""
        lines = self._one("SELECT authz.explain_rule(%s, %s, %s, %s::jsonb)",
                          (table, command, None if id_ is None else _id(id_),
                           None if row is None else json.dumps(row, default=str)))
        return None if lines is None else _texts(lines)

    def expect(self, result: Result, table: str, command: str, id_: Id, row: Row | None = None) -> Result:
        """The result of an UPDATE or DELETE (a row, rows, a count, or the cursor that ran it: its rowcount):
        returned if anything changed, otherwise NotFound (you can't see the row, or the rule allows the write and
        the statement matched nothing for another reason) or Refused (you may not, and why)."""
        count = getattr(result, "rowcount", None)
        if count > 0 if isinstance(count, int) and not isinstance(count, bool) else bool(result):
            return result
        why = self.explain_rule(table, command, id_, row)
        if why is None or (why and why[0].lstrip().startswith("yes")):
            raise NotFound(table, _shown(id_))
        who = self._one(_WHO, ())
        raise Refused(f"permission denied: {{who}} may not {{command}} row {{_shown(id_)}} of {{table}}", table, command, why)

    @staticmethod
    def refusal(error: BaseException) -> Refused | None:
        return refusal(error)

    def who_among(self, type_: ObjectType, id_: Id, perm: Permission, principals: Sequence[Id],
                  principal_type: str = "user") -> Sequence[str]:
        """Which of these people (or principals of another type) hold perm: one call, for live updates. Signs each
        one in, so it needs what signing in needs (SET on authz.user_id)."""
        self._check(type_, perm)
        return self._all("SELECT x FROM authz.who_among(%s, %s::text, %s, %s::text[], %s) x",
                         (type_, _id(id_), perm, [_id(p) for p in principals], principal_type))
'''


# the constants the Ruby names and their signatures name inside the module Authz: a type's module of one of these
# names would be the one they meant there
RUBY_TAKEN = {"Rowstile", "Hash", "Array", "String"}


def _ruby_names(perms: Perms) -> dict[str, tuple[str, dict[str, str]]]:
    """{type: (its module, {permission: its constant})}: Project and EDIT for project's edit (org_unit and orgUnit
    are OrgUnit, manage_keys and manageKeys MANAGE_KEYS). A type whose module would be another's, or isn't a
    Ruby constant, or is one the files name in Authz (RUBY_TAKEN), gets none; nor does a permission whose constant
    would be another's of its type, or TYPE (the module's constant for the type's own name)."""
    module: Callable[[str], str] = lambda t: "".join(p[:1].upper() + p[1:] for p in t.split("_"))
    constant: Callable[[str], str] = lambda p: re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", p).lstrip("_").upper()
    modules: dict[str, list[str]] = {}
    for t in perms:
        modules.setdefault(module(t), []).append(t)
    out: dict[str, tuple[str, dict[str, str]]] = {}
    for t, ps in perms.items():
        m = module(t)
        if len(modules[m]) > 1 or not re.fullmatch(r"[A-Z]\w*", m) or m in RUBY_TAKEN:
            continue
        consts: dict[str, list[str]] = {}
        for p in ps:
            consts.setdefault(constant(p), []).append(p)
        out[t] = (
            m,
            {p: c for c, same in consts.items() for p in same if len(same) == 1 and c[:1].isalpha() and c != "TYPE"},
        )
    return out


def _client_ruby(perms: Perms, shared: Shared, scopes: list[str], source_name: str, rbs: bool) -> str:
    """For apps on the Ruby SDK (the rowstile gem): the policy's names as constants (rowstile client ruby), and
    their signatures (rowstile client rbs), whose literal types make Steep refuse a misspelled type or permission,
    in the constants and in the SDK's own calls (Authz.queries)."""
    q: Callable[[str], str] = json.dumps
    names = _ruby_names(perms)
    head = f"# Generated by rowstile client from {source_name}. Do not edit; re-run after changing the policy.\n"
    if rbs:
        union: Callable[[list[str]], str] = lambda xs: " | ".join(q(x) for x in xs) if xs else "String"
        all_perms = sorted({p for ps in perms.values() for p in ps})
        lines = [
            head + "# The signatures of the names rowstile client ruby writes: Steep refuses a misspelled one.",
            "module Authz",
            f"  type object_type = {union(list(perms))}",
            f"  type permission = {union(all_perms)}",
        ]
        for t, (m, _) in names.items():
            lines.append(f"  type {re.sub(r'(?<!^)(?=[A-Z])', '_', m).lower()}_permission = {union(perms[t])}")
        lines.append(f"  type scope = {union(scopes)}")
        lines += [
            "",
            "  PERMISSIONS: Hash[object_type, Array[permission]]",
            "  SHARED_RELATIONS: Hash[String, Hash[String, Array[String]]]",
            "  SCOPES: Array[scope]",
        ]
        for t, (m, consts) in names.items():
            lines += ["", f"  module {m}", f"    TYPE: {q(t)}"]
            lines += [f"    {c}: {q(p)}" for p, c in consts.items()]
            lines.append("  end")
        lines += [
            "",
            "  # the SDK's questions, taking only the policy's names",
            "  def self.queries: () -> Rowstile::Queries[object_type, permission]",
            "end",
        ]
        return "\n".join(lines) + "\n"
    listed: Callable[[list[str]], str] = lambda xs: "[" + ", ".join(q(x) for x in xs) + "].freeze"
    lines = [
        "# frozen_string_literal: true",
        "",
        head
        + "# The policy's names, for the Ruby SDK (the rowstile gem). With their signatures (rowstile client rbs),",
        '# Steep refuses a misspelled type or permission: Authz::Note::EDIT, Authz.queries.can("note", 1, "edit").',
        "module Authz",
        "  PERMISSIONS = {",
        *[f"    {q(t)} => {listed(ps)}," for t, ps in perms.items()],
        "  }.freeze",
        "  # relations people may share with authz.share(), and with whom (subject type, or type#relation)",
        "  SHARED_RELATIONS = {",
        *[
            f"    {q(t)} => {{ {', '.join(f'{q(r)} => {listed(subs)}' for r, subs in rels.items())} }}.freeze,"
            for t, rels in shared.items()
        ],
        "  }.freeze",
        f"  SCOPES = {listed(scopes)}",
    ]
    for t, (m, consts) in names.items():
        lines += ["", f"  module {m}", f"    TYPE = {q(t)}"]
        lines += [f"    {c} = {q(p)}" for p, c in consts.items()]
        lines.append("  end")
    lines += [
        "",
        "  # the SDK's questions (can, perms_of, permitted), taking only the policy's names",
        "  def self.queries = Rowstile::Queries.new",
        "end",
    ]
    return "\n".join(lines) + "\n"


# Elixir's reserved words, and the functions every module has or each type's module defines: no permission's name
ELIXIR_TAKEN = {"true", "false", "nil", "when", "and", "or", "not", "in", "fn", "do", "end", "catch", "rescue"}
ELIXIR_TAKEN |= {"after", "else", "type", "module_info"}
# no type's module: inside the names' module, its alias would hide the SDK's (Rowstile), or Elixir's own (Kernel, whose
# macros the modules after it expand to)
ELIXIR_MODULES_TAKEN = {"Rowstile", "Kernel"}


def _elixir_names(perms: Perms) -> tuple[dict[str, tuple[str, dict[str, str]]], list[str]]:
    """({type: (its module, {permission: its function})}, what has no name, said in a comment): Project and edit
    for project's edit (org_unit and orgUnit are OrgUnit, manage_keys and manageKeys manage_keys). A type whose
    module would be another's, or isn't an Elixir alias, or is one of ELIXIR_MODULES_TAKEN, gets none; nor does a permission whose function would be another's of its type, or isn't a function's
    name (a reserved word, type: the type's own)."""
    module: Callable[[str], str] = lambda t: "".join(p[:1].upper() + p[1:] for p in t.split("_"))
    function: Callable[[str], str] = lambda p: re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", p).lower()
    modules: dict[str, list[str]] = {}
    for t in perms:
        modules.setdefault(module(t), []).append(t)
    out: dict[str, tuple[str, dict[str, str]]] = {}
    unnamed: list[str] = []
    for t, ps in perms.items():
        m = module(t)
        if len(modules[m]) > 1 or not re.fullmatch(r"[A-Z][A-Za-z0-9_]*", m) or m in ELIXIR_MODULES_TAKEN:
            unnamed.append(t)
            continue
        functions: dict[str, list[str]] = {}
        for p in ps:
            functions.setdefault(function(p), []).append(p)
        named = {
            p: f
            for f, same in functions.items()
            for p in same
            if len(same) == 1 and re.fullmatch(r"[a-z][a-z0-9_]*", f) and f not in ELIXIR_TAKEN
        }
        unnamed += [f"{t}.{p}" for p in ps if p not in named]
        out[t] = (m, named)
    return out, unnamed


def _client_elixir(perms: Perms, shared: Shared, scopes: list[str], module: str, source_name: str) -> str:
    """For apps on the Elixir SDK (rowstile on Hex): the policy's names as functions, a module for each type, so
    that a misspelled type or permission is an undefined function, and a plain string the compiler's type error,
    in the SDK's own calls (Rowstile.can?/3 takes a Rowstile.Permission). Laid out as mix format lays it out."""
    q: Callable[[str], str] = json.dumps
    names, unnamed = _elixir_names(perms)

    def listed(xs: list[str], indent: str, before: int = 0) -> list[str]:
        """A list on one line when it fits well within mix format's 98 columns (`before` of them are taken), else one
        item a line (mix format keeps a list written so)."""
        one = "[" + ", ".join(q(x) for x in xs) + "]"
        if before + len(one) <= 90:
            return [one]
        return ["[", *[f"{indent}  {q(x)}," for x in xs[:-1]], f"{indent}  {q(xs[-1])}", f"{indent}]"]

    def entries(pairs: list[tuple[str, list[str]]], indent: str) -> list[str]:
        """The entries of a map whose values are lists, one entry a line, each list as listed() writes it."""
        lines: list[str] = []
        for i, (key, xs) in enumerate(pairs):
            first, *rest = listed(xs, indent, len(f"{indent}{q(key)} => ,"))
            comma = "," if i < len(pairs) - 1 else ""
            item = [f"{indent}{q(key)} => {first}", *rest]
            item[-1] += comma
            lines += item
        return lines

    def mapping(lines: list[str], indent: str) -> list[str]:
        return ["%{}"] if not lines else ["%{", *lines, f"{indent}}}"]

    def shared_entries() -> list[str]:
        lines: list[str] = []
        for i, (t, rels) in enumerate(shared.items()):
            inner = mapping(entries(list(rels.items()), "        "), "      ")
            item = [f"      {q(t)} => {inner[0]}", *inner[1:]]
            item[-1] += "," if i < len(shared) - 1 else ""
            lines += item
        return lines

    def body(spec: str, name: str, value: list[str]) -> list[str]:
        """A function of no argument returning the value: on one line when the value is, else a do block."""
        if len(value) == 1:
            return [f"  @spec {name}() :: {spec}", f"  def {name}, do: {value[0]}"]
        return [f"  @spec {name}() :: {spec}", f"  def {name} do", *[f"    {x}" for x in value], "  end"]

    perm_lines = mapping(entries(list(perms.items()), "      "), "    ")
    scope_lines = listed(scopes, "    ", len("  def scopes, do: "))
    lines = [
        f"# Generated by rowstile client from {source_name}. Do not edit; re-run after changing the policy.",
        f"defmodule {module} do",
        '  @moduledoc """',
        "  The policy's names, for the Elixir SDK (rowstile): a module for each type, a function for each permission,",
        "  so that a misspelled one doesn't compile, and the SDK's calls take only these:",
        f"  `Rowstile.can?(repo, {module}.Note.edit(), id)`.",
        '  """',
        "",
        '  @doc "Each type\'s permissions."',
        *body("%{String.t() => [String.t()]}", "permissions", [x.removeprefix("    ") for x in perm_lines]),
        "",
        '  @doc "The relations people may share with authz.share(), and with whom (a subject type, or type#relation)."',
        *body(
            "%{String.t() => %{String.t() => [String.t()]}}",
            "shared_relations",
            [x.removeprefix("    ") for x in mapping(shared_entries(), "    ")],
        ),
        "",
        '  @doc "The scopes an API key or a session may be limited to."',
        *body("[String.t()]", "scopes", [x.removeprefix("    ") for x in scope_lines]),
    ]
    if unnamed:
        lines += ["", f"  # no name in Elixir: {', '.join(unnamed)} (%Rowstile.Permission{{type: type, name: name}})"]
    for t, (m, functions) in names.items():
        lines += [
            "",
            f"  defmodule {m} do",
            f'    @moduledoc "The type {t}, and its permissions."',
            "",
            "    @spec type() :: Rowstile.ObjectType.t()",
            f"    def type, do: %Rowstile.ObjectType{{name: {q(t)}}}",
        ]
        for p, f in functions.items():
            lines += [
                "",
                "    @spec " + f + "() :: Rowstile.Permission.t()",
                f"    def {f}, do: %Rowstile.Permission{{type: {q(t)}, name: {q(p)}}}",
            ]
        lines.append("  end")
    lines.append("end")
    return "\n".join(lines) + "\n"
