#!/usr/bin/env python3
"""Manage the five named InstaBox machines through the official CLI."""
import argparse
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import time


def main():
    parser = argparse.ArgumentParser(description="批量管理 InstaBox，默认 ib-1 到 ib-5")
    parser.add_argument("action", choices=["status", "up", "down", "exec"])
    parser.add_argument("command", nargs="?", help="exec 使用的远程 shell 命令，整体加引号")
    args = parser.parse_args()
    if (args.action == "exec") != (args.command is not None):
        parser.error("仅 exec 需要一个加引号的命令参数")
    cli = shutil.which("instabox")
    if not cli:
        parser.error("请先安装官方 instabox CLI")
    env = os.environ.copy()
    if not env.get("INSTABOX_API_KEY"):
        keyfile = Path.home() / ".config/instabox/api-key"
        if keyfile.is_file():
            env["INSTABOX_API_KEY"] = keyfile.read_text().strip()
    names = os.environ.get("INSTABOX_MACHINES", "ib-1 ib-2 ib-3 ib-4 ib-5").split()
    if not names or len(names) != len(set(names)):
        parser.error("INSTABOX_MACHINES 不能为空或包含重复名称")

    def call(argv, capture=False):
        return subprocess.run([cli, *argv], env=env, text=True,
                              stdout=subprocess.PIPE if capture else None,
                              check=False, timeout=240)

    def operate(argv):
        # Retry only an explicit rate-limit rejection; never replay a timeout.
        for attempt in range(3):
            result = call([*argv, "--json"], capture=True)
            if result.returncode == 0:
                print("操作完成", flush=True)
                return True
            print(result.stdout, end="", flush=True)
            try:
                error = json.loads(result.stdout).get("error", {})
            except ValueError:
                return False
            if error.get("code") != "rate_limited" or attempt == 2:
                return False
            delay = max(1, int(error.get("retryAfterSeconds") or 60))
            print(f"平台限速，等待 {delay} 秒后重试", flush=True)
            while delay:
                step = min(60, delay)
                time.sleep(step)
                delay -= step
        return False

    failed = []
    for name in names:
        print(f"\n[{name}]", flush=True)
        try:
            result = call(["get", name, "--json"], capture=True)
            if result.returncode:
                print(result.stdout, end="", flush=True)
                failed.append(name)
                continue
            info = json.loads(result.stdout)
            state = info["state"].lower()
            if args.action == "status":
                print(state, flush=True)
                continue
            operation = None
            if args.action == "up":
                if state == "suspended":
                    operation = ["resume", name]
                elif state == "stopped":
                    operation = ["start", name]
                elif state == "running":
                    print("已经运行，跳过", flush=True)
                else:
                    raise ValueError(f"实例正在变化或异常：{state}，稍后重试")
            elif args.action == "down":
                if state == "running":
                    operation = ["suspend", name]
                elif state in ("suspended", "stopped"):
                    print(f"当前 {state}，跳过", flush=True)
                else:
                    raise ValueError(f"实例正在变化或异常：{state}，稍后重试")
            else:
                if state != "running":
                    raise ValueError(f"当前 {state}，请先运行 ib-all up")
                operation = ["exec", name, "--", args.command]
            if operation:
                ok = (call(operation).returncode == 0 if args.action == "exec"
                      else operate(operation))
                if not ok:
                    failed.append(name)
        except (OSError, ValueError, KeyError, subprocess.TimeoutExpired) as exc:
            print(f"失败：{exc}", file=sys.stderr, flush=True)
            failed.append(name)
    if failed:
        print("\n失败实例：" + ", ".join(failed), file=sys.stderr)
        return 1
    print("\n全部完成", flush=True)
    return 0


if __name__ == "__main__":
    sys.exit(main())
