#!/usr/bin/env python3
"""Aditivo y seguro:
  1) agrega el campo bool 'urgente' a la colección pedidos (si falta).
  2) crea la colección 'consultas' (consultas/reclamos por pedido).
No toca datos existentes 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")


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 cid(token, name):
    code, data = req("GET", f"/api/collections/{name}", token=token)
    return (data["id"], data) if code == 200 else (None, None)


def main():
    if not EMAIL or not PASS:
        print("FATAL: set PB_ADMIN_EMAIL / PB_ADMIN_PASSWORD", file=sys.stderr); sys.exit(1)
    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"]

    pedidos_id, pedidos = cid(token, "pedidos")
    users_id, _ = cid(token, "users")
    if not pedidos_id or not users_id:
        print("FATAL: faltan pedidos/users", file=sys.stderr); sys.exit(1)

    # 1) urgente en pedidos (aditivo)
    fields = pedidos.get("fields", [])
    if any(f.get("name") == "urgente" for f in fields):
        print("pedidos.urgente ya existe")
    else:
        fields.append({"name": "urgente", "type": "bool", "required": False})
        code, d = req("PATCH", f"/api/collections/{pedidos_id}", token=token, body={"fields": fields})
        print("pedidos.urgente agregado" if code < 300 else f"pedidos PATCH FAIL {code} {d}")

    # 2) consultas
    schema = {
        "name": "consultas",
        "type": "base",
        "fields": [
            {"name": "pedido", "type": "relation", "required": True,
             "collectionId": pedidos_id, "maxSelect": 1, "cascadeDelete": True, "presentable": True},
            {"name": "tipo", "type": "select", "required": True,
             "values": ["consulta", "reclamo"], "maxSelect": 1},
            {"name": "nota", "type": "text", "required": False, "max": 2000},
            {"name": "fecha", "type": "text", "required": False, "max": 10},
            {"name": "created_by", "type": "relation", "required": False,
             "collectionId": users_id, "maxSelect": 1, "cascadeDelete": False},
        ],
        "listRule":   "@request.auth.id != ''",
        "viewRule":   "@request.auth.id != ''",
        "createRule": "@request.auth.id != ''",
        "updateRule": "@request.auth.id != ''",
        "deleteRule": "@request.auth.id != ''",
        "indexes": [
            "CREATE INDEX idx_consultas_pedido ON consultas (pedido)",
            "CREATE INDEX idx_consultas_fecha  ON consultas (fecha)",
        ],
    }
    existing = req("GET", "/api/collections/consultas", token=token)
    if existing[0] == 200:
        body = dict(schema); body["id"] = existing[1]["id"]
        code, d = req("PATCH", f"/api/collections/{existing[1]['id']}", token=token, body=body)
        print("consultas updated" if code < 300 else f"consultas update FAIL {code} {d}")
    else:
        code, d = req("POST", "/api/collections", token=token, body=schema)
        print("consultas created" if code < 300 else f"consultas create FAIL {code} {d}")


if __name__ == "__main__":
    main()
