#!/usr/bin/env python3
"""Diagnóstico rápido del estado de PocketBase KQ."""
import json, urllib.request, urllib.error, getpass

PB_URL = "http://localhost:8091"

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

email    = input("Email admin: ").strip()
password = getpass.getpass("Password: ")

resp  = req("POST", "collections/_superusers/auth-with-password", {"identity": email, "password": password})
token = resp["token"]
print("✓ Autenticado\n")

# Colecciones
cols = req("GET", "collections?perPage=200", token=token)["items"]
print(f"=== Colecciones ({len(cols)}) ===")
for c in cols:
    if not c["name"].startswith("_"):
        print(f"  {c['name']} (id={c['id']})")

# Campos de users — probando ambas keys posibles según versión PB
users_col = next((c for c in cols if c["name"] == "users"), None)
if users_col:
    fields = users_col.get("fields") or users_col.get("schema") or []
    print(f"\n=== Campos de 'users' ({len(fields)}) ===")
    for f in fields:
        print(f"  {f.get('name')} ({f.get('type')})")
else:
    print("\n⚠ Colección 'users' no encontrada")

# Usuarios
try:
    users = req("GET", "collections/users/records?perPage=50", token=token)
    print(f"\n=== Usuarios ({users['totalItems']}) ===")
    for u in users["items"]:
        print(f"  {u.get('email')} | rol={u.get('rol','—')} | name={u.get('name','—')}")
except RuntimeError as e:
    print(f"\n⚠ No se pudo listar usuarios: {e}")
