#!/usr/bin/env python3
"""
设置admin用户为管理员
"""
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app.core.database import SessionLocal
from app.models.user import User
from app.models.permission import Role

def set_admin():
    """设置admin用户为管理员"""
    db = SessionLocal()
    try:
        print("=" * 60)
        print("设置admin用户为管理员")
        print("=" * 60)
        print()
        
        # 查找admin用户
        admin_user = db.query(User).filter(User.username == "admin").first()
        
        if not admin_user:
            print("❌ 未找到admin用户，请先创建admin用户")
            return
        
        print(f"找到用户: {admin_user.username} (ID: {admin_user.id})")
        print(f"当前角色: {admin_user.role}")
        print()
        
        # 设置role字段为admin
        admin_user.role = "admin"
        print("✅ 已将role字段设置为admin")
        
        # 如果存在admin角色，也分配给用户
        admin_role = db.query(Role).filter(Role.name == "admin").first()
        if admin_role:
            # 检查用户是否已经有admin角色
            if admin_role not in admin_user.roles:
                admin_user.roles.append(admin_role)
                print("✅ 已分配admin角色给用户")
            else:
                print("ℹ️  用户已有admin角色")
        else:
            print("ℹ️  admin角色不存在（可能需要先运行init_rbac_data.py）")
        
        db.commit()
        print()
        print("=" * 60)
        print("✅ admin用户已设置为管理员！")
        print("=" * 60)
        print()
        print("用户信息：")
        print(f"  用户名: {admin_user.username}")
        print(f"  邮箱: {admin_user.email}")
        print(f"  角色: {admin_user.role}")
        if admin_user.roles:
            print(f"  RBAC角色: {', '.join([r.name for r in admin_user.roles])}")
        
    except Exception as e:
        db.rollback()
        print(f"❌ 设置失败: {e}")
        import traceback
        traceback.print_exc()
    finally:
        db.close()


if __name__ == "__main__":
    set_admin()
