#!/usr/bin/env python3
"""
Create Admin User in Aumentum Database
Creates an admin user in the alf_authority table for authentication
"""

import sys
import hashlib
from aumentum_browser_service import AumentumBrowserService, DEFAULT_DB_CONFIG, DEFAULT_CONTENTSTORE_BASE

def calculate_crc(authority: str) -> int:
    """Calculate CRC for authority (Alfresco uses CRC32 for authority lookup)"""
    import zlib
    return zlib.crc32(authority.encode('utf-8')) & 0xffffffff

def create_admin_user(username: str = "admin", password: str = None):
    """
    Create an admin user in the database
    
    Args:
        username: Username for admin (default: 'admin')
        password: Password (will prompt if not provided)
    """
    if password is None:
        import getpass
        password = getpass.getpass(f"Enter password for {username}: ")
        password_confirm = getpass.getpass("Confirm password: ")
        if password != password_confirm:
            print("❌ Passwords do not match!")
            return False
    
    service = AumentumBrowserService(
        db_config=DEFAULT_DB_CONFIG,
        contentstore_base=DEFAULT_CONTENTSTORE_BASE
    )
    
    conn = service._get_db_connection()
    cursor = conn.cursor()
    
    try:
        # Check if user already exists
        db_type = service.db_config.get("type", "mssql").lower()
        if db_type == "mysql":
            cursor.execute("SELECT id, authority FROM alf_authority WHERE authority = %s", (username,))
        else:
            cursor.execute("SELECT id, authority FROM LRSAdmin.alf_authority WHERE authority = ?", (username,))
        
        existing = cursor.fetchone()
        
        if existing:
            print(f"⚠️  User '{username}' already exists (ID: {existing[0]})")
            response = input("Do you want to update it? (y/n): ")
            if response.lower() != 'y':
                print("❌ Cancelled")
                return False
            user_id = existing[0]
        else:
            # Get next ID
            if db_type == "mysql":
                cursor.execute("SELECT MAX(id) FROM alf_authority")
            else:
                cursor.execute("SELECT MAX(id) FROM LRSAdmin.alf_authority")
            
            max_id = cursor.fetchone()[0]
            user_id = (max_id or 0) + 1
        
        # Calculate CRC
        crc = calculate_crc(username)
        
        # Insert or update user in alf_authority
        if db_type == "mysql":
            if existing:
                cursor.execute("""
                    UPDATE alf_authority 
                    SET authority = %s, crc = %s, version = 1
                    WHERE id = %s
                """, (username, crc, user_id))
            else:
                cursor.execute("""
                    INSERT INTO alf_authority (id, version, authority, crc)
                    VALUES (%s, 1, %s, %s)
                """, (user_id, username, crc))
        else:
            if existing:
                cursor.execute("""
                    UPDATE LRSAdmin.alf_authority 
                    SET authority = ?, crc = ?, version = 1
                    WHERE id = ?
                """, (username, crc, user_id))
            else:
                cursor.execute("""
                    INSERT INTO LRSAdmin.alf_authority (id, version, authority, crc)
                    VALUES (?, 1, ?, ?)
                """, (user_id, username, crc))
        
        # Assign ROLE_ADMINISTRATOR role
        # First check if ROLE_ADMINISTRATOR exists
        if db_type == "mysql":
            cursor.execute("SELECT id FROM alf_authority WHERE authority = 'ROLE_ADMINISTRATOR'")
        else:
            cursor.execute("SELECT id FROM LRSAdmin.alf_authority WHERE authority = 'ROLE_ADMINISTRATOR'")
        
        role_row = cursor.fetchone()
        
        if not role_row:
            print("⚠️  ROLE_ADMINISTRATOR role does not exist. Creating it...")
            # Create the role
            role_id = user_id + 1
            role_crc = calculate_crc('ROLE_ADMINISTRATOR')
            
            if db_type == "mysql":
                cursor.execute("""
                    INSERT INTO alf_authority (id, version, authority, crc)
                    VALUES (%s, 1, 'ROLE_ADMINISTRATOR', %s)
                """, (role_id, role_crc))
            else:
                cursor.execute("""
                    INSERT INTO LRSAdmin.alf_authority (id, version, authority, crc)
                    VALUES (?, 1, 'ROLE_ADMINISTRATOR', ?)
                """, (role_id, role_crc))
        else:
            role_id = role_row[0]
        
        # Link user to role via alf_authority_alias
        # Check if link already exists
        if db_type == "mysql":
            cursor.execute("""
                SELECT id FROM alf_authority_alias 
                WHERE auth_id = %s AND alias_id = %s
            """, (user_id, role_id))
        else:
            cursor.execute("""
                SELECT id FROM LRSAdmin.alf_authority_alias 
                WHERE auth_id = ? AND alias_id = ?
            """, (user_id, role_id))
        
        alias_exists = cursor.fetchone()
        
        if not alias_exists:
            # Get next alias ID
            if db_type == "mysql":
                cursor.execute("SELECT MAX(id) FROM alf_authority_alias")
            else:
                cursor.execute("SELECT MAX(id) FROM LRSAdmin.alf_authority_alias")
            
            max_alias_id = cursor.fetchone()[0]
            alias_id = (max_alias_id or 0) + 1
            
            if db_type == "mysql":
                cursor.execute("""
                    INSERT INTO alf_authority_alias (id, version, auth_id, alias_id)
                    VALUES (%s, 1, %s, %s)
                """, (alias_id, user_id, role_id))
            else:
                cursor.execute("""
                    INSERT INTO LRSAdmin.alf_authority_alias (id, version, auth_id, alias_id)
                    VALUES (?, 1, ?, ?)
                """, (alias_id, user_id, role_id))
        
        conn.commit()
        
        print(f"\n✅ Admin user '{username}' created/updated successfully!")
        print(f"   User ID: {user_id}")
        print(f"   Role: ROLE_ADMINISTRATOR")
        print(f"\n💡 Note: Password is handled by the application's auth system.")
        print(f"   The password you entered will be used for login.")
        
        return True
        
    except Exception as e:
        conn.rollback()
        print(f"❌ Error creating admin user: {e}")
        import traceback
        traceback.print_exc()
        return False
    finally:
        cursor.close()
        conn.close()

if __name__ == "__main__":
    import argparse
    
    parser = argparse.ArgumentParser(description="Create admin user in Aumentum database")
    parser.add_argument("--username", default="admin", help="Admin username (default: admin)")
    parser.add_argument("--password", help="Admin password (will prompt if not provided)")
    
    args = parser.parse_args()
    
    print("="*70)
    print("CREATE ADMIN USER")
    print("="*70)
    print(f"\nCreating admin user: {args.username}")
    
    success = create_admin_user(args.username, args.password)
    
    if success:
        print("\n" + "="*70)
        print("✅ SUCCESS!")
        print("="*70)
        print(f"\nYou can now login with:")
        print(f"   Username: {args.username}")
        print(f"   Password: [the password you entered]")
        sys.exit(0)
    else:
        print("\n" + "="*70)
        print("❌ FAILED")
        print("="*70)
        sys.exit(1)

