import json
from itertools import islice

import click

from ..client import HLJSONEncoder, iter_users


@click.group("user")
@click.pass_context
def user_group(ctx):
    pass


@user_group.command("list")
@click.option(
    "--format",
    type=click.Choice(["table", "json"]),
    default="table",
    show_default=True,
    help="Output format",
)
@click.option("--limit", type=int, default=None, help="Maximum number of users to return")
@click.pass_context
def list_user_command(ctx, format, limit):
    """List users from cloud."""
    client = ctx.obj["client"]
    users_iter = iter_users(client)
    users = list(users_iter) if limit is None else list(islice(users_iter, limit))

    if format == "json":
        click.echo(json.dumps([user.model_dump(mode="json") for user in users], indent=2, cls=HLJSONEncoder))
        return

    if not users:
        click.echo("No users found.")
        return

    click.echo(f"Users from cloud ({len(users)} total):")
    click.echo()
    for i, user in enumerate(users, 1):
        click.echo(f"{i}. {user.email}")
        click.echo(f"   ID: {user.id}")
        if user.uuid:
            click.echo(f"   UUID: {user.uuid}")
        if user.display_name:
            click.echo(f"   Display Name: {user.display_name}")
        click.echo()
