#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
from datetime import datetime

# Add the parent directory to path so we can import the app
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, parent_dir)

from app import app
from models import db, User

def list_users():
    """List all users in the database."""
    with app.app_context():
        try:
            users = User.query.all()
            if not users:
                print("No users found in the database.")
                return []
            
            print("Found {} users:".format(len(users)))
            print("-" * 60)
            print("{:<5} {:<20} {:<30} {:<10}".format("ID", "Username", "Email", "Admin"))
            print("-" * 60)
            
            for user in users:
                print("{:<5} {:<20} {:<30} {:<10}".format(
                    user.id, user.username, user.email, "Yes" if user.is_admin else "No"
                ))
            return users
        except Exception as e:
            print(f"Error listing users: {e}")
            return []

def create_user(username, email, password, is_admin=False):
    """Create a new user in the database."""
    with app.app_context():
        try:
            # Check if user already exists
            existing_user = User.query.filter_by(username=username).first()
            if existing_user:
                print(f"User with username '{username}' already exists.")
                return False
            
            # Check if email already exists
            existing_email = User.query.filter_by(email=email).first()
            if existing_email:
                print(f"User with email '{email}' already exists.")
                return False
            
            # Create new user
            user = User(
                username=username,
                email=email,
                is_admin=is_admin,
                created_at=datetime.utcnow()
            )
            user.set_password(password)
            
            db.session.add(user)
            db.session.commit()
            
            print(f"User '{username}' created successfully!")
            return True
            
        except Exception as e:
            db.session.rollback()
            print(f"Error creating user: {e}")
            return False

def reset_password(username, new_password):
    """Reset password for a user."""
    with app.app_context():
        try:
            user = User.query.filter_by(username=username).first()
            if not user:
                print(f"User '{username}' not found.")
                return False
            
            user.set_password(new_password)
            db.session.commit()
            
            print(f"Password for user '{username}' reset successfully!")
            return True
            
        except Exception as e:
            db.session.rollback()
            print(f"Error resetting password: {e}")
            return False

def delete_user(username):
    """Delete a user from the database."""
    with app.app_context():
        try:
            user = User.query.filter_by(username=username).first()
            if not user:
                print(f"User '{username}' not found.")
                return False
            
            db.session.delete(user)
            db.session.commit()
            
            print(f"User '{username}' deleted successfully!")
            return True
            
        except Exception as e:
            db.session.rollback()
            print(f"Error deleting user: {e}")
            return False

def create_admin_user():
    """Create an admin user in the database."""
    return create_user('admin', 'admin@example.com', 'admin', is_admin=True)

if __name__ == "__main__":
    import argparse
    
    parser = argparse.ArgumentParser(description='User management utility')
    subparsers = parser.add_subparsers(dest='command', help='Command to execute')
    
    # List users command
    list_parser = subparsers.add_parser('list', help='List all users')
    
    # Create user command
    create_parser = subparsers.add_parser('create', help='Create a new user')
    create_parser.add_argument('--username', '-u', required=True, help='Username')
    create_parser.add_argument('--email', '-e', required=True, help='Email address')
    create_parser.add_argument('--password', '-p', required=True, help='Password')
    create_parser.add_argument('--admin', '-a', action='store_true', help='Make user an admin')
    
    # Reset password command
    reset_parser = subparsers.add_parser('reset-password', help='Reset a user password')
    reset_parser.add_argument('--username', '-u', required=True, help='Username')
    reset_parser.add_argument('--password', '-p', required=True, help='New password')
    
    # Delete user command
    delete_parser = subparsers.add_parser('delete', help='Delete a user')
    delete_parser.add_argument('--username', '-u', required=True, help='Username to delete')
    
    # Create admin command (shortcut)
    admin_parser = subparsers.add_parser('create-admin', help='Create the default admin user')
    
    args = parser.parse_args()
    
    if args.command == 'list':
        list_users()
    elif args.command == 'create':
        create_user(args.username, args.email, args.password, args.admin)
    elif args.command == 'reset-password':
        reset_password(args.username, args.password)
    elif args.command == 'delete':
        delete_user(args.username)
    elif args.command == 'create-admin':
        create_admin_user()
    else:
        parser.print_help() 