#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
清理脚本 - 用于删除无关的文件和日志
"""

import os
import shutil
import glob

def clean_logs():
    """清理日志文件"""
    print("清理日志文件...")
    
    # 删除.active文件
    active_files = glob.glob("logs/*.active")
    for file in active_files:
        try:
            os.remove(file)
            print(f"已删除: {file}")
        except Exception as e:
            print(f"删除文件时出错 {file}: {e}")
    
    # 保留最新的日志，删除旧的备份
    log_files = glob.glob("logs/*.log.*")
    for file in log_files:
        try:
            os.remove(file)
            print(f"已删除: {file}")
        except Exception as e:
            print(f"删除文件时出错 {file}: {e}")

def clean_temp_files():
    """清理临时文件"""
    print("清理临时文件...")
    
    # 清空临时目录
    temp_dir = "data/temp"
    if os.path.exists(temp_dir):
        for file in os.listdir(temp_dir):
            file_path = os.path.join(temp_dir, file)
            try:
                if os.path.isfile(file_path):
                    os.remove(file_path)
                    print(f"已删除: {file_path}")
                elif os.path.isdir(file_path):
                    shutil.rmtree(file_path)
                    print(f"已删除目录: {file_path}")
            except Exception as e:
                print(f"删除文件时出错 {file_path}: {e}")
    
    # 删除备份文件
    backup_files = glob.glob("data/*.bak") + glob.glob("config/*.bak")
    for file in backup_files:
        try:
            os.remove(file)
            print(f"已删除: {file}")
        except Exception as e:
            print(f"删除文件时出错 {file}: {e}")

def clean_pycache():
    """清理Python缓存文件"""
    print("清理Python缓存文件...")
    
    # 查找并删除所有__pycache__目录
    for root, dirs, files in os.walk("."):
        for dir in dirs:
            if dir == "__pycache__":
                cache_dir = os.path.join(root, dir)
                try:
                    shutil.rmtree(cache_dir)
                    print(f"已删除目录: {cache_dir}")
                except Exception as e:
                    print(f"删除目录时出错 {cache_dir}: {e}")

def main():
    """主函数"""
    print("开始清理无关文件...")
    
    clean_logs()
    clean_temp_files()
    clean_pycache()
    
    print("清理完成！")

if __name__ == "__main__":
    main() 