import yaml
import os

def load_images(file_path):
    """从指定文件加载镜像列表，支持过滤注释和空行"""
    images = []
    try:
        with open(file_path, "r", encoding="utf-8") as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith("#"):
                    images.append(line)
        return images
    except FileNotFoundError:
        print(f"错误：镜像列表文件 {file_path} 不存在")
        exit(1)

# 配置参数
IMAGE_LIST_FILE = "images.txt"  # 镜像列表文件路径
OUTPUT_DIR = "images"              # 输出目录
OUTPUT_FILE = "index.yaml"        # 输出文件名        

# 从文件加载镜像列表
raw_images = load_images(IMAGE_LIST_FILE)

# 转换处理
result = []
for idx, image in enumerate(raw_images, 1):
    try:
        # 分离镜像名和标签
        if image.count(":") != 1:
            raise ValueError("镜像格式不符合 name:tag 规范")

        image_name, tag = image.split(":")
        name_segment = image_name.split("/")[-1]

        # 生成文件名 (替换非法文件名字符)
        safe_tag = tag.replace("/", "_").replace(" ", "_")
        filename = f"{name_segment}_{safe_tag}.tar"

        result.append({
            "name": image,
            "path": f"./{filename}"
        })
    except Exception as e:
        print(f"第 {idx} 行解析失败: {image} ({str(e)})")
        continue

# 创建输出目录
os.makedirs(OUTPUT_DIR, exist_ok=True)

# 写入 YAML 文件
output_path = os.path.join(OUTPUT_DIR, OUTPUT_FILE)
with open(output_path, "w", encoding="utf-8") as f:
    yaml.dump(
        {"images": result},
        f,
        default_flow_style=False,
        sort_keys=False,
        indent=2,
        allow_unicode=True
    )

print(f"转换完成！共处理 {len(result)} 个镜像")
print(f"输出文件路径: {os.path.abspath(output_path)}")
