#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import os
import re

# 章节标题映射（根据内容生成合适的subtitle）
subtitle_map = {
    1: '初入阿拉德', 2: '剑士之路', 3: '鬼手觉醒', 4: '格兰之森', 5: '牛头巨兽',
    6: '幽暗密林', 7: '猛毒雷鸣', 8: '冰霜幽暗', 9: '烈焰格拉卡', 10: '暗黑雷鸣',
    11: '天空之城', 12: '龙人之塔', 13: '人偶玄关', 14: '石巨人塔', 15: '黑暗玄廊',
    16: '城主宫殿', 17: '光之城主', 18: '西海岸', 19: '天帷巨兽', 20: '神殿外围',
    21: '树精丛林', 22: '炼狱', 23: '极昼', 24: '第一脊椎', 25: '第二脊椎',
    26: 'GBL教', 27: '奥菲利亚', 28: '阿法利亚', 29: '蜘蛛洞穴', 30: '浅栖之地',
    31: '摩根之谜', 32: '暗精灵', 33: '熔岩穴', 34: '暗影迷宫', 35: '邪龙封印',
    36: '雪山之旅', 37: '冰心少年', 38: '山脊', 39: '利库天井', 40: '白色废墟',
    41: '布万加', 42: '敏泰', 43: '班图族', 44: '斯卡萨', 45: '冰雪宫殿',
    46: '斯顿雪域', 47: 'GBL女神殿', 48: '树精繁殖地', 49: '堕落之殿', 50: '诺斯玛尔',
    51: '盗贼团', 52: '哈穆林', 53: '鼠王', 54: '迷乱之村', 55: '血蝴蝶',
    56: '帕丽丝', 57: '月光酒馆', 58: '索西雅', 59: '死亡之塔', 60: '迷惘之塔',
    61: '绝望之塔', 62: '莎兰', 63: '西海岸风云', 64: '暗精灵战争', 65: '克伦特',
    66: '暗黑城', 67: '暗影迷宫', 68: '无头骑士', 69: '悲鸣洞穴', 70: '启程天界',
    71: '根特外围', 72: '卡勒特', 73: '皇女艾丽婕', 74: '泽丁', 75: '马琳',
    76: '夜间袭击', 77: '补给线阻断', 78: '追击歼灭', 79: '夜间奇袭', 80: '夺回东门',
    81: '夺回南门', 82: '北门反击', 83: '根特防御', 84: '卡勒特总部', 85: '兰蒂卢斯',
    86: '海上列车', 87: '莫斯提马', 88: '斯曼工业', 89: '安徒恩', 90: '攻坚战',
    91: '使徒陨落'
}

updated_count = 0

for i in range(1, 92):
    # 确定文件名格式
    if i <= 9:
        filename = f'chapter-0{i}.json'
    else:
        filename = f'chapter-{i}.json'
    
    filepath = os.path.join('.', filename)
    
    if not os.path.exists(filepath):
        print(f'文件不存在: {filename}')
        continue
    
    with open(filepath, 'r', encoding='utf-8') as f:
        data = json.load(f)
    
    # 检查是否需要更新
    needs_update = False
    
    # 添加subtitle
    if 'subtitle' not in data or not data['subtitle']:
        data['subtitle'] = subtitle_map.get(i, f'第{i}章')
        needs_update = True
    
    # 添加desc（从content提取前100字符）
    if 'desc' not in data or not data['desc']:
        content = data.get('content', '')
        # 提取第一段，去除换行和多余空格
        first_para = content.split('\n')[0].strip()
        # 清理内容，只保留纯文本
        first_para = re.sub(r'["\'\n\t]', '', first_para)
        # 截取前100字符
        desc = first_para[:100] + '...' if len(first_para) > 100 else first_para
        data['desc'] = desc
        needs_update = True
    
    if needs_update:
        with open(filepath, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
        updated_count += 1
        print(f'已更新: {filename}')
    else:
        print(f'无需更新: {filename}')

print(f'\n总共更新了 {updated_count} 个文件')
