#!/usr/bin/env python3
"""
Script to create specific users for the SIM Analytics system
"""

import os
import hashlib
import psycopg2

def get_db_connection():
    """Get PostgreSQL database connection"""
    return psycopg2.connect(os.environ['DATABASE_URL'])

def hash_password(password):
    """Hash password using SHA-256"""
    return hashlib.sha256(password.encode()).hexdigest()

def create_user(username, password, role):
    """Create a new user"""
    conn = get_db_connection()
    cursor = conn.cursor()
    
    try:
        password_hash = hash_password(password)
        
        # Check if user already exists
        cursor.execute("SELECT COUNT(*) FROM users WHERE username = %s", (username,))
        if cursor.fetchone()[0] > 0:
            print(f"User {username} already exists, updating password...")
            cursor.execute("""
                UPDATE users SET password_hash = %s, role = %s
                WHERE username = %s
            """, (password_hash, role, username))
        else:
            cursor.execute("""
                INSERT INTO users (username, password_hash, role)
                VALUES (%s, %s, %s)
            """, (username, password_hash, role))
            print(f"Created new user: {username} with role: {role}")
        
        conn.commit()
        return True
    except Exception as e:
        print(f"Error creating user {username}: {e}")
        return False
    finally:
        cursor.close()
        conn.close()

def main():
    print("Creating custom users...")
    
    # Create admin user
    success1 = create_user("ceo@openweb.co.za", "Maniac20!", "admin")
    
    # Create staff user
    success2 = create_user("ceo@openweb.email", "Maniac20!", "staff")
    
    if success1 and success2:
        print("\nUsers created successfully!")
        print("Admin user: ceo@openweb.co.za")
        print("Staff user: ceo@openweb.email")
    else:
        print("Some users failed to create.")

if __name__ == "__main__":
    main()