#!/usr/bin/env python3
import json
import os

# 读取 index.json 文件
index_path = "books/末日重生-开局囤货十亿物资/chapters/index.json"
with open(index_path, 'r', encoding='utf-8') as f:
    data = json.load(f)

print(f"原始数据长度: {len(data)}")

# 检查每个元素是否有 title
fixed_data = []
for i, item in enumerate(data):
    if not isinstance(item, dict):
        print(f"第 {i+1} 个元素不是字典: {item}")
        continue
    
    # 确保有 title 字段
    if 'title' not in item:
        print(f"第 {i+1} 个元素缺少 title: {item}")
        # 尝试从其他字段推断 title
        if 'number' in item:
            item['title'] = f"第{item['number']}章"
        else:
            item['title'] = f"章节{i+1}"
    
    # 确保其他必需字段
    if 'number' not in item:
        item['number'] = i + 1
    
    fixed_data.append(item)

print(f"修复后数据长度: {len(fixed_data)}")

# 保存修复后的文件
with open(index_path, 'w', encoding='utf-8') as f:
    json.dump(fixed_data, f, ensure_ascii=False, indent=2)

print("修复完成！")