# SPDX-FileCopyrightText: 2026 Martin Kirchgessner
#
# SPDX-License-Identifier: AGPL-3.0-or-later

import click

from . import radiotomate_cli


@radiotomate_cli.group()
def users():
    """
    Users management commands
    """


@users.command()
def roles():
    """
    List role identifiers, that can be used with --role
    """
    from radiotomate.enums import Role

    for role in Role:
        click.echo(role)


ROLES_HELP = (
    "Set role. List available roles with the `roles` command. "
    "Repeat the option for each role you want to grant."
)


def _process_roles(user, role):
    from radiotomate.enums import Role

    roles = {}
    for r in role:
        if r not in Role:
            msg = (
                f"Role name '{r}' does not exist. "
                "Call `radiotomate user roles` to list possible values."
            )
            click.UsageError(msg)
        roles["can_" + r] = "true"
    user.update_roles(roles)


@users.command()
@click.argument("username")
@click.password_option()
@click.option("--admin", is_flag=True, help="Give admin rights to this account")
@click.option("--role", multiple=True, help=ROLES_HELP)
@click.pass_obj
def add(config, username, password, role, admin=False):
    """
    Create a radiotomate user account
    """
    import asyncio

    from radiotomate.db import QuartAlchemy
    from radiotomate.models import User

    db = QuartAlchemy()
    db.init_from_config(config["db"], {})
    user = User(username=username)
    user.update_password(password)

    if admin or "admin" in role:
        user.update_roles({"can_admin": "true"})
    else:
        _process_roles(user, role)

    async def do_add(session):
        async with session.begin() as dbsession:
            dbsession.add(user)

    asyncio.run(do_add(db.session))


@users.command()
@click.argument("username")
@click.password_option(
    prompt_required=False,
    help="If you prefer entering it interactively, "
    "write `--password` alone after the username.",
)
@click.option(
    "--role",
    multiple=True,
    help=ROLES_HELP + "Existing roles are untouched if the option is not used, "
    "but once one is provided other roles will be revoked.",
)
@click.pass_obj
def mod(config, username, password, role):
    """
    Change the password of a radiotomate user
    """
    import asyncio

    from radiotomate.db import QuartAlchemy
    from radiotomate.models import User

    db = QuartAlchemy()
    db.init_from_config(config["db"], {})

    async def do_mod(session):
        async with session.begin() as dbsession:
            user = await User.from_username(dbsession, username)
            if user:
                if password:
                    user.update_password(password)
                if role:
                    _process_roles(user, role)
            else:
                click.echo(f"User {username} not found")
                raise click.exceptions.Exit(1)

    asyncio.run(do_mod(db.session))


@users.command()
@click.argument("username")
@click.pass_obj
def rm(config, username):
    """
    Remove a radiotomate user account
    """
    import asyncio

    from radiotomate.db import QuartAlchemy
    from radiotomate.models import User

    db = QuartAlchemy()
    db.init_from_config(config["db"], {})

    async def do_mod(session):
        async with session.begin() as dbsession:
            user = await User.from_username(dbsession, username)
            if user:
                await dbsession.delete(user)
            else:
                click.echo(f"User {username} not found")
                raise click.exceptions.Exit(1)

    asyncio.run(do_mod(db.session))
