# retoor <retoor@molodetz.nl>

import sys
from devplacepy.database import get_table
from devplacepy.cli._shared import _audit_cli


def cmd_apikey_get(args):
    users = get_table("users")
    user = users.find_one(username=args.username)
    if not user:
        print(f"User '{args.username}' not found")
        sys.exit(1)
    print(user.get("api_key", "") or "")


def cmd_apikey_reset(args):
    from devplacepy.utils import generate_uid, clear_user_cache

    users = get_table("users")
    user = users.find_one(username=args.username)
    if not user:
        print(f"User '{args.username}' not found")
        sys.exit(1)
    new_key = generate_uid()
    users.update({"uid": user["uid"], "api_key": new_key}, ["uid"])
    clear_user_cache(user["uid"])
    from devplacepy.services.audit import record as audit

    _audit_cli(
        "cli.apikey.reset",
        f"CLI regenerated the API key of user {args.username}",
        target_type="user",
        target_uid=user["uid"],
        target_label=args.username,
        links=[audit.target("user", user["uid"], args.username)],
    )
    print(new_key)


def cmd_apikey_backfill(args):
    from devplacepy.database import backfill_api_keys

    updated = backfill_api_keys()
    _audit_cli(
        "cli.apikey.backfill",
        f"CLI backfilled API keys for {updated} users",
        metadata={"count": updated},
    )
    print(f"Assigned API keys to {updated} user(s) without one")


def register_apikeys(subparsers):
    apikey = subparsers.add_parser("apikey", help="Manage user API keys")
    apikey_sub = apikey.add_subparsers(title="action", dest="action")
    apikey_get = apikey_sub.add_parser("get", help="Print a user's API key")
    apikey_get.add_argument("username")
    apikey_get.set_defaults(func=cmd_apikey_get)
    apikey_reset = apikey_sub.add_parser("reset", help="Regenerate a user's API key")
    apikey_reset.add_argument("username")
    apikey_reset.set_defaults(func=cmd_apikey_reset)
    apikey_backfill = apikey_sub.add_parser(
        "backfill", help="Assign API keys to users that lack one"
    )
    apikey_backfill.set_defaults(func=cmd_apikey_backfill)
