#!/usr/bin/env python3
"""
更新章节索引文件，确保inkos知道最新章节
"""

import json
import os
from datetime import datetime

def update_chapter_index():
    """更新章节索引"""
    print("更新章节索引文件...")
    
    # 章节文件目录
    chapters_dir = "/root/.openclaw/workspace/tomato-novel/tomato-novel/books/末日重生-开局囤货十亿物资/chapters"
    
    # 获取所有章节文件
    chapter_files = []
    for f in os.listdir(chapters_dir):
        if f.endswith('.md') and f[0].isdigit():
            chapter_files.append(f)
    
    chapter_files.sort()
    print(f"找到 {len(chapter_files)} 个章节文件")
    
    # 创建索引数据
    index_data = []
    for filename in chapter_files:
        try:
            # 从文件名提取信息
            # 格式: 0136_危机升级.md
            parts = filename.split('_')
            if len(parts) >= 2 and parts[0].isdigit():
                chapter_num = int(parts[0])
                title = parts[1].replace('.md', '')
                
                # 读取文件内容统计字数
                file_path = os.path.join(chapters_dir, filename)
                with open(file_path, 'r', encoding='utf-8') as f:
                    content = f.read()
                    word_count = len(content)
                
                # 创建索引条目
                index_entry = {
                    "number": chapter_num,
                    "title": title,
                    "status": "ready-for-review",
                    "wordCount": word_count,
                    "createdAt": datetime.now().isoformat() + 'Z',
                    "updatedAt": datetime.now().isoformat() + 'Z',
                    "auditIssues": [],
                    "lengthWarnings": [],
                    "lengthTelemetry": {
                        "target": 3000,
                        "softMin": 2591,
                        "softMax": 3409,
                        "hardMin": 2182,
                        "hardMax": 3818,
                        "countingMode": "zh_chars",
                        "writerCount": word_count,
                        "postWriterNormalizeCount": word_count,
                        "postReviseCount": 0,
                        "finalCount": word_count,
                        "normalizeApplied": False,
                        "lengthWarning": False
                    },
                    "tokenUsage": {
                        "promptTokens": 0,
                        "completionTokens": 0,
                        "totalTokens": 0
                    }
                }
                
                index_data.append(index_entry)
                print(f"  添加第{chapter_num}章: {title} ({word_count}字)")
        except Exception as e:
            print(f"  处理文件 {filename} 时出错: {e}")
    
    # 按章节号排序
    index_data.sort(key=lambda x: x['number'])
    
    # 保存索引文件
    index_path = os.path.join(chapters_dir, "index.json")
    with open(index_path, 'w', encoding='utf-8') as f:
        json.dump(index_data, f, ensure_ascii=False, indent=2)
    
    print(f"\n✅ 索引文件已更新: {index_path}")
    print(f"   总章节数: {len(index_data)}")
    
    if index_data:
        print(f"   章节范围: 第{index_data[0]['number']}章 - 第{index_data[-1]['number']}章")
        
        # 显示最近5章
        print("\n最近5章:")
        for entry in index_data[-5:]:
            print(f"   第{entry['number']}章: {entry['title']}")

def create_simple_book_json():
    """创建简单的book.json文件"""
    print("\n创建简单book.json...")
    
    book_data = {
        "id": "末日重生-开局囤货十亿物资",
        "title": "末日重生：开局囤货十亿物资",
        "platform": "tomato",
        "genre": "urban",
        "language": "zh",
        "targetChapters": 200,
        "currentChapter": 143,
        "status": "active",
        "createdAt": datetime.now().isoformat() + 'Z',
        "updatedAt": datetime.now().isoformat() + 'Z',
        "settings": {
            "wordCountPerChapter": {
                "target": 3000,
                "min": 2500,
                "max": 3500
            },
            "quality": {
                "enforcement": "none"
            }
        }
    }
    
    book_path = "/root/.openclaw/workspace/tomato-novel/tomato-novel/books/末日重生-开局囤货十亿物资/book.json"
    os.makedirs(os.path.dirname(book_path), exist_ok=True)
    
    with open(book_path, 'w', encoding='utf-8') as f:
        json.dump(book_data, f, ensure_ascii=False, indent=2)
    
    print(f"✅ book.json 已创建: {book_path}")

def main():
    """主函数"""
    print("=" * 60)
    print("更新章节索引和book.json文件")
    print("=" * 60)
    
    try:
        update_chapter_index()
        create_simple_book_json()
        
        print("\n" + "=" * 60)
        print("✅ 更新完成!")
        print("=" * 60)
        print("\ninkos现在应该知道有143章内容，可以继续创作第144章了。")
        
    except Exception as e:
        print(f"\n❌ 更新失败: {e}")

if __name__ == "__main__":
    main()