import json
import sys
import os

def fix_index_json(filepath):
    try:
        with open(filepath, 'r', encoding='utf-8') as f:
            data = json.load(f)
        
        if not isinstance(data, list):
            print(f"数据结构不是数组，而是 {type(data)}")
            return
        
        fixed_count = 0
        
        for i, item in enumerate(data):
            if not item.get('title') or str(item.get('title', '')).strip() == '':
                # 生成一个默认标题
                chapter_num = item.get('number', i+1)
                item['title'] = f"第{chapter_num}章"
                fixed_count += 1
                print(f"修复第 {i+1} 项 (章节号: {chapter_num}) - 标题设置为: {item['title']}")
        
        if fixed_count > 0:
            # 备份原文件
            backup_path = filepath + '.backup_fix'
            with open(backup_path, 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=2)
            print(f"已创建备份: {backup_path}")
            
            # 写入修复后的文件
            with open(filepath, 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=2)
            print(f"修复完成，修复了 {fixed_count} 个空标题")
        else:
            print("没有发现空标题，无需修复")
            
    except Exception as e:
        print(f"处理文件时出错: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)

if __name__ == "__main__":
    index_path = "books/末日重生-开局囤货十亿物资/chapters/index.json"
    if os.path.exists(index_path):
        fix_index_json(index_path)
    else:
        print(f"文件不存在: {index_path}")
