#!/usr/bin/env python3
"""
fix_users.py — Actualiza o crea la cuenta de Ale (teacher).
"""
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()}")

print("=== fix_users.py — Kings & Queens ===\n")

admin_email    = input("Email superuser admin: ").strip()
admin_password = getpass.getpass("Password superuser: ")

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

# Listar usuarios actuales
users = req("GET", "collections/users/records?perPage=50", token=token)
print(f"Usuarios actuales ({users['totalItems']}):")
for u in users["items"]:
    print(f"  [{u['id']}] {u.get('email')} | rol={u.get('rol','—')} | name={u.get('name','—')}")

print("\n¿Qué querés hacer?")
print("  1) Actualizar el usuario teacher existente (cambiar email, nombre, contraseña)")
print("  2) Crear usuario teacher nuevo")
opcion = input("Opción [1/2]: ").strip()

if opcion == "1":
    uid = input("ID del usuario a actualizar (copiá de la lista): ").strip()
    new_email = input("Nuevo email: ").strip()
    new_name  = input("Nombre para mostrar [Ale]: ").strip() or "Ale"
    new_pass  = getpass.getpass("Nueva contraseña (min 8 chars): ")

    updated = req("PATCH", f"collections/users/records/{uid}", {
        "email":           new_email,
        "name":            new_name,
        "password":        new_pass,
        "passwordConfirm": new_pass,
        "rol":             "teacher",
        "emailVisibility": True,
    }, token=token)

    print(f"\n✅ Usuario actualizado:")
    print(f"   email: {updated['email']}")
    print(f"   name:  {updated.get('name')}")
    print(f"   rol:   {updated.get('rol')}")

elif opcion == "2":
    new_email = input("Email: ").strip()
    new_name  = input("Nombre para mostrar [Ale]: ").strip() or "Ale"
    new_pass  = getpass.getpass("Contraseña (min 8 chars): ")

    created = req("POST", "collections/users/records", {
        "email":           new_email,
        "password":        new_pass,
        "passwordConfirm": new_pass,
        "name":            new_name,
        "rol":             "teacher",
        "emailVisibility": True,
    }, token=token)

    print(f"\n✅ Usuario creado:")
    print(f"   email: {created['email']}")
    print(f"   name:  {created.get('name')}")
    print(f"   rol:   {created.get('rol')}")

print(f"\nProbá entrar en: http://localhost:8080/app/kings-and-queens/app/")
