#!/usr/bin/env python3
"""Backend admin tool for Advanced Glass Design Studio's user/credit system.

Run this directly on the server (SSH, or cPanel's Terminal app) — it talks
straight to the same users.json file the web app reads, so the app does not
need to be running.

Usage:
    python manage_users.py create   <username> <password> [starting_credits]
    python manage_users.py add      <username> <amount>        # add credits (negative to remove)
    python manage_users.py set      <username> <amount>        # set balance to an exact number
    python manage_users.py passwd   <username> <new_password>
    python manage_users.py delete   <username>
    python manage_users.py list

Examples:
    python manage_users.py create rafiq secret123 50
    python manage_users.py add rafiq 20
    python manage_users.py set rafiq 100
    python manage_users.py list
"""
from __future__ import annotations

import sys

import users_store


def main() -> int:
    args = sys.argv[1:]
    if not args:
        print(__doc__)
        return 1

    cmd = args[0]

    try:
        if cmd == "create":
            if len(args) < 3:
                print("Usage: python manage_users.py create <username> <password> [starting_credits]")
                return 1
            username, password = args[1], args[2]
            credits = int(args[3]) if len(args) > 3 else 0
            users_store.create_user(username, password, credits)
            print(f"Created '{username}' with {credits} credit(s).")

        elif cmd == "add":
            if len(args) != 3:
                print("Usage: python manage_users.py add <username> <amount>")
                return 1
            username, amount = args[1], int(args[2])
            balance = users_store.add_credits(username, amount)
            print(f"'{username}' now has {balance} credit(s).")

        elif cmd == "set":
            if len(args) != 3:
                print("Usage: python manage_users.py set <username> <amount>")
                return 1
            username, amount = args[1], int(args[2])
            balance = users_store.set_credits(username, amount)
            print(f"'{username}' balance set to {balance} credit(s).")

        elif cmd == "passwd":
            if len(args) != 3:
                print("Usage: python manage_users.py passwd <username> <new_password>")
                return 1
            username, new_password = args[1], args[2]
            if not users_store.change_password(username, new_password):
                print(f"No such user: '{username}'")
                return 1
            print(f"Password updated for '{username}'.")

        elif cmd == "delete":
            if len(args) != 2:
                print("Usage: python manage_users.py delete <username>")
                return 1
            username = args[1]
            if not users_store.delete_user(username):
                print(f"No such user: '{username}'")
                return 1
            print(f"Deleted '{username}'.")

        elif cmd == "list":
            rows = users_store.list_users()
            if not rows:
                print("No users yet. Create one with: python manage_users.py create <username> <password> [credits]")
                return 0
            name_w = max(len("username"), max(len(r["username"]) for r in rows))
            print(f"{'username'.ljust(name_w)}  credits  created_at")
            for r in rows:
                print(f"{r['username'].ljust(name_w)}  {str(r['credits']).rjust(7)}  {r.get('created_at', '')}")

        else:
            print(f"Unknown command: '{cmd}'\n")
            print(__doc__)
            return 1

    except ValueError as exc:
        print(f"Error: {exc}")
        return 1

    return 0


if __name__ == "__main__":
    raise SystemExit(main())
