import os
import sys
import subprocess
from pathlib import Path

# 获取当前脚本所在目录，确保相对路径正确
BASE_DIR = Path(__file__).parent.resolve()

# 定义菜单项：(显示名称, 对应的脚本文件名)
MENU_ITEMS = [
    ("安装/更新 Node.js & npm", "npm-manager.ps1"),
    ("清理并重装 DeepSeek Harness", "dsh-manager.ps1"),
    ("一键启动 DeepSeek Harness", "startDSH.ps1"),
]

def clear_screen():
    """清屏，兼容 Windows 和 Linux"""
    os.system('cls' if os.name == 'nt' else 'clear')

def print_banner():
    """打印工具箱横幅"""
    print("\033[96m" + "="*45)
    print("       ️  DeepSeek Harness 自动化工具箱")
    print("="*45 + "\033[0m")

def run_powershell_script(script_name: str):
    """
    调用 PowerShell 执行脚本
    使用 -ExecutionPolicy Bypass 避免用户本地策略限制
    """
    script_path = BASE_DIR / script_name
    
    if not script_path.exists():
        print(f"\n\033[91m[ERROR] 未找到脚本: {script_path}\033[0m")
        print("请确保脚本与 toolbox.py 在同一目录下。")
        input("按回车键返回菜单...")
        return

    print(f"\n\033[93m[INFO] 正在执行: {script_name} ...\033[0m")
    print("-" * 45)
    
    try:
        # 启动 PowerShell 子进程，实时输出日志
        subprocess.run(
            ["powershell.exe", "-ExecutionPolicy", "Bypass", "-File", str(script_path)],
            check=False
        )
    except KeyboardInterrupt:
        print("\n\033[93m[WARN] 用户中断了当前任务。\033[0m")
    except Exception as e:
        print(f"\n\033[91m[ERROR] 执行出错: {e}\033[0m")
        
    input("\n按回车键返回菜单...")

def show_menu():
    """主菜单循环"""
    while True:
        clear_screen()
        print_banner()
        
        for idx, (name, _) in enumerate(MENU_ITEMS, start=1):
            print(f"  \033[92m[{idx}]\033[0m {name}")
        print(f"  \033[91m[0]\033[0m 退出工具箱")
        
        choice = input("\n请输入选项编号: ").strip()
        
        if choice == '0':
            print("\n\033[96m再见！\033[0m")
            sys.exit(0)
        elif choice.isdigit() and 1 <= int(choice) <= len(MENU_ITEMS):
            script_name = MENU_ITEMS[int(choice) - 1][1]
            run_powershell_script(script_name)
        else:
            print("\n\033[91m[ERROR] 无效的输入，请重新选择。\033[0m")
            input("按回车键继续...")

if __name__ == "__main__":
    show_menu()