from __future__ import annotations

import sys
from typing import Optional, Sequence, TextIO

from . import __version__
from .commands import COMMANDS, run_named_command
from .doctor import format_doctor_report, format_version_report
from .menu import run_super_menu


def print_help(file: Optional[TextIO] = None) -> None:
    out = file or sys.stdout
    commands = [
        ("all [args...]", "运行原版 all.sh；如果第一个参数以 - 开头，也会自动走这个入口"),
        ("step1 [args...]", "运行 v1/step1.sh"),
        ("step2 [args...]", "运行 v1/step2.sh"),
        ("step3 [args...]", "运行 v1/step3.sh"),
        ("ai [args...]", "运行 v1/step_ai.sh"),
        ("git [args...]", "运行 v1/step_git.sh"),
        ("diff [args...]", "运行 v1/step_diff.sh"),
        ("vpn [args...]", "运行 v1/step_vpn.sh"),
        ("doctor", "输出当前 runtime、bundle、工作仓库和源同步状态"),
        ("version", "输出包版本和 bundle 版本"),
        ("menu", "强制进入超级菜单"),
    ]

    print("Usage: lehome [COMMAND] [ARGS...]", file=out)
    print("", file=out)
    print("默认行为：", file=out)
    print("  `lehome` 在交互终端中进入超级菜单；非交互环境下打印本帮助。", file=out)
    print("", file=out)
    print("Commands:", file=out)
    for name, description in commands:
        print(f"  {name:<16} {description}", file=out)
    print("", file=out)
    print("Examples:", file=out)
    print("  lehome", file=out)
    print("  lehome all --list", file=out)
    print("  lehome step2", file=out)
    print("  lehome doctor", file=out)
    print("  lehome version", file=out)
    print("", file=out)
    print(f"Package version: {__version__}", file=out)


def main(argv: Optional[Sequence[str]] = None) -> int:
    args = list(sys.argv[1:] if argv is None else argv)

    if not args:
        if sys.stdin.isatty() and sys.stdout.isatty():
            return run_super_menu()
        print_help()
        return 0

    first, rest = args[0], args[1:]

    if first in {"-h", "--help", "help"}:
        print_help()
        return 0
    if first in {"-V", "--version"}:
        print(format_version_report())
        return 0
    if first == "version":
        print(format_version_report())
        return 0
    if first == "doctor":
        print(format_doctor_report())
        return 0
    if first == "menu":
        return run_super_menu()
    if first in COMMANDS:
        return run_named_command(first, rest)
    if first.startswith("-"):
        return run_named_command("all", args)

    print(f"未知命令: {first}", file=sys.stderr)
    print_help(sys.stderr)
    return 2
