import argparse
import logging
import secrets

from unwind import db, models, utils

log = logging.getLogger(__name__)

name = "add-user"
help = "Add a new user."


def add_args(cmd: argparse.ArgumentParser) -> None:
    cmd.add_argument("--name", required=True)
    cmd.add_argument("--imdb-id", required=True)
    cmd.add_argument(
        "--overwrite-existing",
        action="store_true",
        help="Allow overwriting an existing user.  WARNING: This will reset the user's password!",
    )


async def main(args: argparse.Namespace) -> None:
    user_id: str = args.imdb_id
    name: str = args.name
    overwrite_existing: bool = args.overwrite_existing

    if not user_id.startswith("ur"):
        raise ValueError(f"Invalid IMDb user ID: {user_id!a}")

    await db.open_connection_pool()

    async with db.new_connection() as conn:
        user = await db.get(conn, models.User, imdb_id=user_id)

    if user is not None:
        if overwrite_existing:
            log.warning("⚠️ Overwriting existing user: %a", user)
        else:
            log.error("❌ User already exists: %a", user)
            return

    secret = secrets.token_bytes()

    user = models.User(name=name, imdb_id=user_id, secret=utils.phc_scrypt(secret))
    async with db.transaction() as conn:
        await db.add_or_update_user(conn, user)

    user_data = {
        "secret": utils.b64encode(secret),
        "user": models.asplain(user),
    }

    log.info("✨ User created: %a", user_data)

    await db.close_connection_pool()
