import os
import sys
import importlib
import traceback
from datetime import datetime

def run_tool(tool_name):
    """运行指定的工具脚本"""
    print(f"\n{'='*50}")
    print(f"开始执行 {tool_name}")
    print(f"{'='*50}")
    
    start_time = datetime.now()
    print(f"开始时间: {start_time.strftime('%Y-%m-%d %H:%M:%S')}")
    
    try:
        # 导入工具模块
        module = importlib.import_module(tool_name)
        
        # 执行main函数
        if hasattr(module, 'main'):
            module.main()
            print(f"\n✅ {tool_name} 执行成功")
        else:
            print(f"\n❌ {tool_name} 没有找到main函数")
            return False
            
    except Exception as e:
        print(f"\n❌ {tool_name} 执行失败: {str(e)}")
        traceback.print_exc()
        return False
    
    end_time = datetime.now()
    duration = end_time - start_time
    print(f"结束时间: {end_time.strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"耗时: {duration.total_seconds():.2f} 秒")
    
    return True

def main():
    """主函数：依次执行所有工具"""
    print("开始执行全部数据处理工具 (T1-T8)")
    print(f"当前工作目录: {os.getcwd()}")
    
    # 确保在Tools目录下执行
    tools_dir = os.path.dirname(os.path.abspath(__file__))
    os.chdir(tools_dir)
    print(f"切换到工具目录: {tools_dir}")
    
    # 将Tools目录添加到Python路径
    if tools_dir not in sys.path:
        sys.path.insert(0, tools_dir)
    
    # 将项目根目录添加到Python路径
    project_root = os.path.dirname(tools_dir)
    if project_root not in sys.path:
        sys.path.insert(0, project_root)
    
    # 定义要执行的工具列表
    tools = [
        "T1_RenKou",
        "T2_MaoRuXueLv",
        "T3_SchoolCount",
        "T4_ClassCount",
        "T5_ZhaoShengCount",
        "T6_ZaiXiaoShengCount",
        "T7_TeacherCount",
        "T8_SchoolMianJi"
    ]
    
    # 记录执行结果
    results = {}
    
    # 依次执行每个工具
    for tool in tools:
        success = run_tool(tool)
        results[tool] = success
        
        # 如果某个工具执行失败，可以选择是否继续执行后续工具
        if not success:
            print(f"\n⚠️ {tool} 执行失败，但继续执行后续工具...")
    
    # 打印执行结果摘要
    print("\n" + "="*50)
    print("执行结果摘要")
    print("="*50)
    
    success_count = sum(1 for result in results.values() if result)
    total_count = len(results)
    
    for tool, success in results.items():
        status = "✅ 成功" if success else "❌ 失败"
        print(f"{tool}: {status}")
    
    print(f"\n总计: {success_count}/{total_count} 个工具执行成功")
    
    if success_count == total_count:
        print("🎉 所有工具执行完成！")
    else:
        print("⚠️ 部分工具执行失败，请检查错误信息")

if __name__ == "__main__":
    main()