import os
import sys
from datetime import datetime
from werkzeug.security import generate_password_hash

# Add the current directory to the Python path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

# Import the app and models
from app import create_app, db
from models import User

def create_admin_user(username='admin', email='admin@example.com', password='admin123'):
    """Create an admin user if no admin exists"""
    app = create_app()
    
    with app.app_context():
        # Check if admin user already exists
        existing_admin = User.query.filter_by(role='admin').first()
        
        if existing_admin:
            print(f"Admin user already exists: {existing_admin.username}")
            return
        
        # Create admin user
        admin = User(
            username=username,
            email=email,
            password_hash=generate_password_hash(password),
            role='admin',
            created_at=datetime.utcnow()
        )
        
        db.session.add(admin)
        db.session.commit()
        print(f"Admin user created successfully: {username}")

if __name__ == "__main__":
    # Get command line arguments if provided
    username = sys.argv[1] if len(sys.argv) > 1 else 'admin'
    email = sys.argv[2] if len(sys.argv) > 2 else 'admin@example.com'
    password = sys.argv[3] if len(sys.argv) > 3 else 'admin123'
    
    create_admin_user(username, email, password)
    print(f"You can now login at /admin/login with username: {username} and the provided password")
