import json, urllib.request

PB = "http://localhost:8102"

def post(path, data, token=None):
    req = urllib.request.Request(PB + path, data=json.dumps(data).encode(),
        headers={"Content-Type": "application/json", **({"Authorization": token} if token else {})})
    return json.load(urllib.request.urlopen(req))

def get(path, token=None):
    req = urllib.request.Request(PB + path, headers={"Authorization": token} if token else {})
    return json.load(urllib.request.urlopen(req))

def patch(path, data, token):
    req = urllib.request.Request(PB + path, data=json.dumps(data).encode(),
        headers={"Content-Type": "application/json", "Authorization": token}, method="PATCH")
    return json.load(urllib.request.urlopen(req))

tok = post("/api/collections/_superusers/auth-with-password",
           {"identity": "edelmar.edd@gmail.com", "password": "564712564712"})["token"]

col = get("/api/collections/facturas", tok)
fields = col["fields"]

if any(f["name"] == "comprobante_pdf" for f in fields):
    print("El campo 'comprobante_pdf' YA existe. Nada que hacer.")
else:
    fields.append({
        "name": "comprobante_pdf",
        "type": "file",
        "required": False,
        "presentable": False,
        "maxSelect": 1,
        "maxSize": 5242880,
        "mimeTypes": ["application/pdf"],
        "thumbs": [],
        "protected": False,
    })
    patch(f"/api/collections/{col['id']}", {"fields": fields}, tok)
    print("Campo 'comprobante_pdf' (file, pdf, 5MB) AGREGADO a la coleccion facturas.")
