#!/usr/bin/env python3
import os
import glob
import re
import subprocess
import stat
import platform
import sys

def parse_version(ver_str: str):
    """解析版本号为整数元组"""
    parts = ver_str.split(".")
    nums = [int(p) for p in parts]
    while len(nums) < 3:
        nums.append(0)
    return tuple(nums)

def get_system_arch():
    """获取系统架构: amd64 / arm64"""
    machine = platform.machine().lower()
    if machine in ("x86_64", "amd64"):
        return "amd64"
    elif machine in ("aarch64", "arm64"):
        return "arm64"
    else:
        print(f"不支持的架构: {machine}")
        sys.exit(1)

def main():
    """选择并运行匹配架构的最新版本 bin 文件"""
    arch = get_system_arch()
    print(f"系统架构: {arch}")

    bin_files = glob.glob("miuitask*.bin")
    if not bin_files:
        print("未找到 bin 文件")
        return

    pattern = re.compile(rf"miuitask-v([\d.]+)-linux-{arch}\.bin", re.IGNORECASE)

    candidates = []
    for f in bin_files:
        m = pattern.search(f)
        if m:
            candidates.append((parse_version(m.group(1)), f))

    if not candidates:
        print(f"无匹配 {arch} 文件")
        return

    latest_ver, latest_file = max(candidates, key=lambda x: x[0])
    print(f"运行: {latest_file} (版本 {'.'.join(map(str, latest_ver))})")

    os.chmod(latest_file, os.stat(latest_file).st_mode | stat.S_IEXEC)
    try:
        subprocess.run(["./" + latest_file], check=True)
    except subprocess.CalledProcessError as e:
        print(f"运行失败，退出码 {e.returncode}")

if __name__ == "__main__":
    main()
