#!/usr/bin/env python3
import argparse
import os
import subprocess
try:
    import yaml
except ImportError:
    subprocess.check_call(['pip3', 'install', 'pyyaml'])
    import yaml

# 定义一个用于递归查找文件的函数
def find_files(filename, search_path="."):
    result = []
    for root, dir, files in os.walk(search_path):
        if filename in files:
            result.append(os.path.join(root, filename))
    return result

# 定义一个用于解析pubspec.lock文件的函数
def parse_pubspec_lock(filename):
    with open(filename, "r") as f:
        data = yaml.safe_load(f)
    dependencies = []
    for package, info in data["packages"].items():
        if "url" in info["description"] and "castbox" in info["description"]["url"]:
            dependencies.append(package)
    return dependencies

# 查找所有pubspec.lock文件并解析依赖

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Process some integers.")
    parser.add_argument("--flutter_sdk", type=str, help="android or ios")

    args = parser.parse_args()
    flutter_sdk = args.flutter_sdk

    if flutter_sdk:
        print(f"flutter sdk: {flutter_sdk}")
        os.environ["PATH"] = f"{flutter_sdk}:{os.environ['PATH']}"

    current_dir = os.getcwd()
    dependencies = []
    for file in find_files("pubspec.lock", current_dir):
        deps = parse_pubspec_lock(file)
        if deps:
            rel_path = os.path.relpath(os.path.dirname(file), start=current_dir)
            flutterCmd = "flutter pub upgrade " + " ".join(deps)
            print('[{}] {}'.format(rel_path, flutterCmd))
            cmd = 'cd {} && {} && cd {}'.format(rel_path, flutterCmd, current_dir)
            os.system(cmd)
    os.chdir(current_dir)
