#!/usr/bin/env python3
"""
为简化版API创建测试用户（使用SHA256加密）
"""
import mysql.connector
import hashlib
from datetime import datetime

# 数据库配置
DB_CONFIG = {
    'host': '127.0.0.1',
    'user': 'root',
    'password': '',
    'database': 'kaopeilian',
    'charset': 'utf8mb4',
    'autocommit': True
}

# 要创建的系统账户
SYSTEM_USERS = [
    {
        "username": "superadmin",
        "password": "Superadmin123!",
        "email": "superadmin@kaopeilian.com",
        "full_name": "超级管理员",
        "role": "admin",
        "is_superuser": 1,
    },
    {
        "username": "admin",
        "password": "Admin123!",
        "email": "admin@kaopeilian.com",
        "full_name": "系统管理员",
        "role": "admin",
        "is_superuser": 0,
    },
    {
        "username": "testuser",
        "password": "TestPass123!",
        "email": "testuser@kaopeilian.com",
        "full_name": "测试学员",
        "role": "trainee",
        "is_superuser": 0,
    },
]

def hash_password(password: str) -> str:
    """使用SHA256加密密码（与simple_main.py保持一致）"""
    return hashlib.sha256(password.encode()).hexdigest()

def create_simple_users():
    """创建测试用户"""
    try:
        conn = mysql.connector.connect(**DB_CONFIG)
        cursor = conn.cursor()
        
        print("🔧 开始创建系统测试账户（SHA256版本）...\n")
        
        created_count = 0
        updated_count = 0
        
        for user_data in SYSTEM_USERS:
            username = user_data["username"]
            password_hash = hash_password(user_data["password"])
            
            # 检查用户是否存在
            cursor.execute("SELECT id FROM users WHERE username = %s", (username,))
            existing = cursor.fetchone()
            
            if existing:
                # 更新现有用户
                cursor.execute("""
                    UPDATE users 
                    SET hashed_password = %s,
                        email = %s,
                        full_name = %s,
                        role = %s,
                        is_active = 1,
                        updated_at = NOW()
                    WHERE username = %s
                """, (
                    password_hash,
                    user_data["email"],
                    user_data["full_name"],
                    user_data["role"],
                    username
                ))
                updated_count += 1
                print(f"✓ 更新用户: {username} ({user_data['full_name']})")
            else:
                # 创建新用户
                cursor.execute("""
                    INSERT INTO users (
                        username, email, hashed_password, role, 
                        is_active, full_name, 
                        created_at, updated_at
                    )
                    VALUES (%s, %s, %s, %s, 1, %s, NOW(), NOW())
                """, (
                    username,
                    user_data["email"],
                    password_hash,
                    user_data["role"],
                    user_data["full_name"]
                ))
                created_count += 1
                print(f"✓ 创建用户: {username} ({user_data['full_name']})")
        
        conn.commit()
        
        # 打印总结
        print("\n" + "="*50)
        print("✅ 系统用户创建/更新完成！")
        print(f"新创建用户数: {created_count}")
        print(f"更新用户数: {updated_count}")
        print("\n系统账户信息：")
        print("-"*50)
        print("| 角色       | 用户名     | 密码           | 权限说明                     |")
        print("| ---------- | ---------- | -------------- | ---------------------------- |")
        print("| 超级管理员 | superadmin | Superadmin123! | 系统最高权限，可管理所有功能 |")
        print("| 系统管理员 | admin      | Admin123!      | 可管理除“系统管理”模块外的全部功能（管理员仪表盘、用户管理、岗位管理、系统日志） |")
        print("| 测试学员   | testuser   | TestPass123!   | 可学习课程、参加考试和训练   |")
        print("-"*50)
        
    except mysql.connector.Error as e:
        print(f"❌ 数据库操作失败: {e}")
    finally:
        if 'cursor' in locals():
            cursor.close()
        if 'conn' in locals():
            conn.close()

if __name__ == "__main__":
    create_simple_users()
