import os
import json
import glob

def format_level_files():
    """格式化custom/Json/文件夹下所有level文件为单行紧凑格式"""
    
    # 设置目录路径
    json_dir = "assets/custom/Json"
    
    # 检查目录是否存在
    if not os.path.exists(json_dir):
        print(f"错误：目录 {json_dir} 不存在")
        return
    
    # 获取所有level*.json文件
    level_files = glob.glob(os.path.join(json_dir, "level*.json"))
    
    print(f"找到 {len(level_files)} 个level文件")
    
    # 处理每个文件
    for file_path in level_files:
        try:
            # 读取原始JSON文件
            with open(file_path, 'r', encoding='utf-8') as f:
                data = json.load(f)
            
            # 将数据转换为单行紧凑格式
            compact_json = json.dumps(data, separators=(',', ':'), ensure_ascii=False)
            
            # 写回文件
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(compact_json)
            
            print(f"✓ 已格式化: {os.path.basename(file_path)}")
            
        except json.JSONDecodeError as e:
            print(f"✗ JSON解析错误 {os.path.basename(file_path)}: {e}")
        except Exception as e:
            print(f"✗ 处理错误 {os.path.basename(file_path)}: {e}")

if __name__ == "__main__":
    format_level_files()
    print("格式化完成！")
