#!/usr/bin/env python3
"""
用户清理脚本
删除除admin以外的所有用户，为员工同步做准备
"""

import asyncio
import sys
from pathlib import Path

# 添加项目根目录到Python路径
sys.path.insert(0, str(Path(__file__).parent.parent))

from sqlalchemy import select, delete
from app.core.database import AsyncSessionLocal
from app.models.user import User
from app.core.logger import get_logger

logger = get_logger(__name__)


async def cleanup_users():
    """
    删除除admin以外的所有用户
    保留username='admin'的管理员账号
    """
    async with AsyncSessionLocal() as db:
        try:
            # 查询要删除的用户
            stmt = select(User).where(User.username != 'admin', User.is_deleted == False)
            result = await db.execute(stmt)
            users_to_delete = result.scalars().all()
            
            if not users_to_delete:
                logger.info("没有需要删除的用户")
                return
            
            logger.info(f"准备删除 {len(users_to_delete)} 个用户")
            for user in users_to_delete:
                logger.info(f"  - ID: {user.id}, 用户名: {user.username}, 姓名: {user.full_name}")
            
            # 确认删除
            print("\n⚠️  警告: 将删除以上用户（保留admin）")
            confirm = input("确认删除？(yes/no): ")
            
            if confirm.lower() != 'yes':
                logger.info("取消删除操作")
                return
            
            # 执行软删除
            for user in users_to_delete:
                user.is_deleted = True
                logger.info(f"已软删除用户: {user.username}")
            
            await db.commit()
            logger.info(f"✅ 成功删除 {len(users_to_delete)} 个用户")
            
            # 显示剩余用户
            stmt = select(User).where(User.is_deleted == False)
            result = await db.execute(stmt)
            remaining_users = result.scalars().all()
            
            logger.info(f"\n剩余用户数量: {len(remaining_users)}")
            for user in remaining_users:
                logger.info(f"  - ID: {user.id}, 用户名: {user.username}, 角色: {user.role}")
            
        except Exception as e:
            logger.error(f"清理用户失败: {str(e)}")
            await db.rollback()
            raise


if __name__ == "__main__":
    print("=" * 60)
    print("用户清理脚本")
    print("=" * 60)
    asyncio.run(cleanup_users())

