#!/usr/bin/env python3
"""Regenerate src/services/backendPermissions.txt from the backend catalog.

    ../keluargamart-backend/internal/auth/catalog.go > src/services/backendPermissions.txt

One permission key per line, sorted, so a regenerated file diffs cleanly
against the committed one.

Note the character class includes `_`. Every other namespace in the catalog
is dotted or hyphenated ("system.activity-logs.view"), which makes it easy to
write a class without it and silently drop the whole sales_tracking family —
a mistake that reads as "the frontend has no such permission" and points at
the wrong repo entirely. That is not hypothetical: it is how this very
check was first written.
"""
import re
import sys

# A key is a dotted namespace then an action suffix. Matched inside double
# quotes only, so identifiers in code (Go const names, function calls) are not
# picked up.
KEY = re.compile(r'"([a-z_][a-z0-9_]*(?:\.[a-z0-9_-]+)+)"')


def main(argv):
    if len(argv) != 2:
        sys.exit(f"usage: {argv[0]} <catalog.go>")
    with open(argv[1], encoding="utf-8") as fh:
        source = fh.read()

    keys = {m.group(1) for m in KEY.finditer(source)}
    # Drop prose that happens to look like a key.
    keys = {k for k in keys if not k.endswith(".")}

    if not keys:
        sys.exit("no permission keys found - refusing to write an empty list")
    sys.stdout.write("\n".join(sorted(keys)) + "\n")


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