#!/usr/bin/env python3
"""Aditivo y seguro: agrega 'catalogo' y 'tareas' a los valores del select
'module' de la colección user_permissions (sin tocar datos ni otras colecciones)."""
import json, os, sys, urllib.request, urllib.error

PB_URL = os.environ.get("PB_URL", "http://localhost:8102")
EMAIL = os.environ.get("PB_ADMIN_EMAIL")
PASS = os.environ.get("PB_ADMIN_PASSWORD")
WANT = ["catalogo", "tareas"]


def req(method, path, token=None, body=None):
    headers = {"Content-Type": "application/json"}
    if token:
        headers["Authorization"] = token
    data = json.dumps(body).encode() if body is not None else None
    r = urllib.request.Request(f"{PB_URL}{path}", data=data, method=method, headers=headers)
    try:
        with urllib.request.urlopen(r) as resp:
            return resp.status, json.loads(resp.read().decode() or "{}")
    except urllib.error.HTTPError as e:
        return e.code, json.loads(e.read().decode() or "{}")


def main():
    code, data = req("POST", "/api/collections/_superusers/auth-with-password",
                     body={"identity": EMAIL, "password": PASS})
    if code != 200:
        print(f"FATAL auth: {code} {data}", file=sys.stderr); sys.exit(1)
    token = data["token"]

    code, coll = req("GET", "/api/collections/user_permissions", token=token)
    if code != 200:
        print(f"FATAL get: {code} {coll}", file=sys.stderr); sys.exit(1)

    fields = coll.get("fields", [])
    changed = False
    for f in fields:
        if f.get("name") == "module" and f.get("type") == "select":
            vals = f.get("values", [])
            for w in WANT:
                if w not in vals:
                    vals.append(w); changed = True
            f["values"] = vals
    if not changed:
        print("user_permissions.module ya tenía catalogo/tareas, sin cambios."); return

    code, data = req("PATCH", f"/api/collections/{coll['id']}", token=token, body={"fields": fields})
    print("user_permissions.module actualizado" if code < 300 else f"FAIL {code} {data}")


if __name__ == "__main__":
    main()
