#!/usr/bin/env python3
"""
创建管理员用户脚本
"""
import asyncio
import sys
import os

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

async def create_admin_users():
    """创建管理员用户"""
    try:
        from app.config.database import AsyncSessionLocal
        from app.models.user import User
        from app.core.security import get_password_hash
        from sqlalchemy import select
        
        print("🔧 创建管理员用户...")
        
        # 管理员用户配置
        admin_users = [
            {
                "username": "admin",
                "password": "Admin123!",
                "email": "admin@kaopeilian.com",
                "full_name": "系统管理员",
                "role": "admin",
                "is_superuser": True,
                "is_active": True
            },
            {
                "username": "superadmin",
                "password": "Superadmin123!",
                "email": "superadmin@kaopeilian.com",
                "full_name": "超级管理员",
                "role": "admin",
                "is_superuser": True,
                "is_active": True
            }
        ]
        
        async with AsyncSessionLocal() as session:
            for user_data in admin_users:
                # 检查用户是否已存在
                result = await session.execute(
                    select(User).where(User.username == user_data["username"])
                )
                existing_user = result.scalar_one_or_none()
                
                if existing_user:
                    print(f"⚠️  用户 '{user_data['username']}' 已存在，跳过创建")
                    continue
                
                # 创建新用户
                hashed_password = get_password_hash(user_data["password"])
                user = User(
                    username=user_data["username"],
                    email=user_data["email"],
                    hashed_password=hashed_password,
                    full_name=user_data["full_name"],
                    role=user_data["role"],
                    is_active=user_data["is_active"]
                )
                
                session.add(user)
                await session.commit()
                await session.refresh(user)
                
                print(f"✅ 管理员用户创建成功:")
                print(f"   用户名: {user.username}")
                print(f"   密码: {user_data['password']}")
                print(f"   角色: {user.role}")
                print(f"   邮箱: {user.email}")
                print("   ---")
        
        print("\n🎉 管理员用户创建完成！")
        print("\n📋 登录信息汇总:")
        print("1. 超级管理员: superadmin / Superadmin123!")
        print("2. 系统管理员: admin / Admin123!")
        print("3. 测试学员: testuser / TestPass123!")
        
    except Exception as e:
        print(f"❌ 创建管理员用户失败: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    asyncio.run(create_admin_users())
