import pymysql
import os
import sys
from passlib.hash import bcrypt
from pymysql.cursors import DictCursor

def get_db_connection():
    try:
        return pymysql.connect(
            host=os.getenv("MARIADB_HOST", "127.0.0.1"),
            port=int(os.getenv("MARIADB_PORT", 3306)),
            user=os.getenv("MARIADB_USER", "crumb"),
            password=os.getenv("MARIADB_PASSWORD", "secret"),
            database=os.getenv("MARIADB_DATABASE", "crumbcrm"),
            autocommit=True,
            charset="utf8mb4",
            cursorclass=DictCursor,
        )
    except Exception as e:
        print(f"Error connecting to database: {e}")
        return None

def setup_demo():
    print("🚀 Setting up Demo User...")
    conn = get_db_connection()
    if not conn:
        print("❌ Could not connect to database.")
        sys.exit(1)

    try:
        with conn.cursor() as cursor:
            # Check if demo user exists
            cursor.execute("SELECT id FROM users WHERE email='demo@crumb.local'")
            user = cursor.fetchone()
            
            password_hash = bcrypt.hash("demo123")
            
            if user:
                print("ℹ️  Updating existing demo user...")
                cursor.execute("""
                    UPDATE users 
                    SET user_group='demo', theme='pico-accessible', pass_hash=%s
                    WHERE email='demo@crumb.local'
                """, (password_hash,))
            else:
                print("✨ Creating new demo user...")
                cursor.execute("""
                    INSERT INTO users (email, pass_hash, role, locale, user_group, theme)
                    VALUES ('demo@crumb.local', %s, 'user', 'de', 'demo', 'pico-accessible')
                """, (password_hash,))
                
            print("✅ Demo user setup complete.")
            print("   Email: demo@crumb.local")
            print("   Pass:  demo123")
            print("   Group: demo")
            print("   Theme: pico-accessible")

    except Exception as e:
        print(f"❌ Setup failed: {e}")
        sys.exit(1)
    finally:
        conn.close()

if __name__ == "__main__":
    setup_demo()
