#!/usr/bin/env python3
"""Crea SOLO la colección 'tareas' en PB :8102 (no toca las demás colecciones).
Idempotente: si existe, hace PATCH; si no, POST.

Uso: PB_ADMIN_EMAIL=.. PB_ADMIN_PASSWORD=.. python3 add_tareas.py
"""
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"] if code == 200 else 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 = cid(token, "pedidos")
    users_id = cid(token, "users")
    if not pedidos_id or not users_id:
        print(f"FATAL: faltan colecciones pedidos/users (pedidos={pedidos_id}, users={users_id})", file=sys.stderr)
        sys.exit(1)

    schema = {
        "name": "tareas",
        "type": "base",
        "fields": [
            {"name": "titulo",      "type": "text",   "required": True,  "max": 200, "presentable": True},
            {"name": "tipo",        "type": "select", "required": True,
             "values": ["medir", "comprar", "cortar", "armar", "instalar", "entregar", "llamar", "otra"], "maxSelect": 1},
            {"name": "descripcion", "type": "editor", "required": False},
            {"name": "fecha",       "type": "text",   "required": False, "max": 10},
            {"name": "hora",        "type": "text",   "required": False, "max": 5},
            {"name": "pedido",      "type": "relation", "required": False,
             "collectionId": pedidos_id, "maxSelect": 1, "cascadeDelete": False, "presentable": True},
            {"name": "estado",      "type": "select", "required": True,
             "values": ["pendiente", "hecha"], "maxSelect": 1},
            {"name": "prioridad",   "type": "select", "required": False,
             "values": ["baja", "media", "alta"], "maxSelect": 1},
            {"name": "asignado_a",  "type": "relation", "required": False,
             "collectionId": users_id, "maxSelect": 1, "cascadeDelete": False},
            {"name": "recordatorio_wa", "type": "bool", "required": False},
            {"name": "completada_at",   "type": "date", "required": False},
            {"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_tareas_estado   ON tareas (estado)",
            "CREATE INDEX idx_tareas_fecha     ON tareas (fecha)",
            "CREATE INDEX idx_tareas_pedido    ON tareas (pedido)",
            "CREATE INDEX idx_tareas_tipo      ON tareas (tipo)",
            "CREATE INDEX idx_tareas_asignado  ON tareas (asignado_a)",
        ],
    }

    existing = req("GET", "/api/collections/tareas", token=token)
    if existing[0] == 200:
        body = dict(schema); body["id"] = existing[1]["id"]
        code, data = req("PATCH", f"/api/collections/{existing[1]['id']}", token=token, body=body)
        print("tareas updated" if code < 300 else f"tareas update FAIL {code} {data}")
    else:
        code, data = req("POST", "/api/collections", token=token, body=schema)
        print("tareas created" if code < 300 else f"tareas create FAIL {code} {data}")


if __name__ == "__main__":
    main()
