from __future__ import annotations

import sys

from .commands import run_named_command
from .doctor import format_doctor_report

MENU_CHOICES = {
    "1": ("all", "进入原版 all.sh 主菜单"),
    "2": ("step1", "运行 step1.sh"),
    "3": ("step2", "运行 step2.sh"),
    "4": ("step3", "运行 step3.sh"),
    "5": ("ai", "运行 step_ai.sh"),
    "6": ("git", "运行 step_git.sh"),
    "7": ("diff", "运行 step_diff.sh"),
    "8": ("vpn", "运行 step_vpn.sh"),
    "9": ("doctor", "运行 doctor"),
}


def _print_menu() -> None:
    print()
    print("LeHome CLI")
    print("=========")
    for key, (_, description) in MENU_CHOICES.items():
        print(f"{key}. {description}")
    print("0. 退出")
    print()


def _pause() -> None:
    if sys.stdin.isatty() and sys.stdout.isatty():
        try:
            input("按回车返回超级菜单...")
        except EOFError:
            pass


def run_super_menu() -> int:
    while True:
        try:
            _print_menu()
            choice = input("请选择: ").strip()
        except (EOFError, KeyboardInterrupt):
            print()
            return 0

        if choice in {"0", "", "q", "quit", "exit"}:
            return 0

        if choice == "9":
            print()
            print(format_doctor_report())
            print()
            _pause()
            continue

        item = MENU_CHOICES.get(choice)
        if item is None:
            print("无效选项，请重新输入。")
            continue

        command_name, description = item
        print()
        print(f">>> {description}")
        exit_code = run_named_command(command_name, [])
        print(f">>> 退出码: {exit_code}")
        print()
        _pause()
