#!/bin/bash

echo "=== 小说内容同步到飞书 ==="
echo "时间: $(date)"
echo "小说: 《末日重生-开局囤货十亿物资》"
echo ""

# 配置
NOVEL_DIR="/root/.openclaw/workspace/tomato-novel/books/末日重生-开局囤货十亿物资"
CHAPTERS_DIR="$NOVEL_DIR/chapters"
SYNC_STATE="/root/.openclaw/workspace/novel_sync_state.json"
FEISHU_APP_TOKEN="MkRqbphc2afqEksxf6vcJjZVn8O"
FEISHU_TABLE_ID="tbllH7wGmGbSCtPD"

# 初始化状态文件
if [ ! -f "$SYNC_STATE" ]; then
    cat > "$SYNC_STATE" << EOF
{
  "last_sync": "$(date -Iseconds)",
  "synced_chapters": [],
  "total_chapters": 0,
  "feishu_app_token": "$FEISHU_APP_TOKEN",
  "feishu_table_id": "$FEISHU_TABLE_ID"
}
EOF
    echo "📝 创建同步状态文件: $SYNC_STATE"
fi

# 发现章节文件
echo "🔍 发现章节文件..."
CHAPTER_FILES=$(find "$CHAPTERS_DIR" -name "*.md" -type f | grep -E "^[0-9]{4}_" | sort)
TOTAL_CHAPTERS=$(echo "$CHAPTER_FILES" | wc -l)

echo "📚 发现 $TOTAL_CHAPTERS 个章节文件"
echo ""

# 显示章节列表
echo "📋 章节列表:"
echo "$CHAPTER_FILES" | head -10 | while read -r file; do
    filename=$(basename "$file")
    size=$(wc -c < "$file" 2>/dev/null || echo 0)
    echo "  📄 $filename ($size 字符)"
done

if [ "$TOTAL_CHAPTERS" -gt 10 ]; then
    echo "  ... 还有 $((TOTAL_CHAPTERS - 10)) 个章节"
fi
echo ""

# 创建Python同步脚本
echo "🔄 创建同步脚本..."
cat > /tmp/sync_to_feishu.py << 'PYTHON_EOF'
#!/usr/bin/env python3
"""
同步小说章节到飞书多维表格
"""

import os
import re
import json
import time
from pathlib import Path

def read_sync_state(state_file):
    """读取同步状态"""
    if os.path.exists(state_file):
        with open(state_file, 'r', encoding='utf-8') as f:
            return json.load(f)
    return {"synced_chapters": []}

def save_sync_state(state_file, state):
    """保存同步状态"""
    with open(state_file, 'w', encoding='utf-8') as f:
        json.dump(state, f, ensure_ascii=False, indent=2)

def parse_chapter_info(filename):
    """解析章节信息"""
    # 格式: 0018_钢渣.md
    match = re.match(r'(\d{4})_(.*?)\.md', filename)
    if match:
        return {
            "number": int(match.group(1)),
            "title": match.group(2),
            "filename": filename
        }
    return None

def read_chapter_content(filepath, max_length=10000):
    """读取章节内容"""
    try:
        with open(filepath, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 清理内容
        content = content.replace('\r', '')
        
        # 截断过长的内容
        if len(content) > max_length:
            content = content[:max_length] + "\n\n【内容过长，已截断】"
        
        return content
    except Exception as e:
        return f"读取失败: {e}"

def get_chapter_preview(content, length=200):
    """获取章节预览"""
    # 移除换行和多余空格
    preview = content.replace('\n', ' ').strip()
    preview = re.sub(r'\s+', ' ', preview)
    
    if len(preview) > length:
        preview = preview[:length] + "..."
    
    return preview

def sync_chapter_to_feishu(chapter_info, content, app_token, table_id):
    """同步章节到飞书（模拟）"""
    print(f"  📤 同步第{chapter_info['number']}章: {chapter_info['title']}")
    
    # 这里应该调用飞书API
    # 实际实现需要安装飞书SDK
    
    preview = get_chapter_preview(content)
    
    # 模拟API调用
    print(f"    标题: {chapter_info['title']}")
    print(f"    字数: {len(content)} 字符")
    print(f"    预览: {preview}")
    
    return True

def main():
    """主函数"""
    import sys
    
    if len(sys.argv) < 4:
        print("用法: python3 script.py <章节目录> <状态文件> <应用token> <表格ID>")
        return
    
    chapters_dir = sys.argv[1]
    state_file = sys.argv[2]
    app_token = sys.argv[3]
    table_id = sys.argv[4]
    
    print("=== 开始同步到飞书多维表格 ===")
    
    # 读取状态
    state = read_sync_state(state_file)
    synced = set(state.get("synced_chapters", []))
    
    # 发现新章节
    new_chapters = []
    all_files = list(Path(chapters_dir).glob("*.md"))
    
    for filepath in all_files:
        filename = filepath.name
        chapter_info = parse_chapter_info(filename)
        
        if chapter_info and chapter_info["number"] not in synced:
            # 读取内容
            content = read_chapter_content(str(filepath))
            
            # 同步到飞书
            if sync_chapter_to_feishu(chapter_info, content, app_token, table_id):
                new_chapters.append(chapter_info["number"])
    
    # 更新状态
    if new_chapters:
        state["synced_chapters"].extend(new_chapters)
        state["synced_chapters"] = list(set(state["synced_chapters"]))
        state["last_sync"] = time.strftime("%Y-%m-%d %H:%M:%S")
        state["total_synced"] = len(state["synced_chapters"])
        
        save_sync_state(state_file, state)
        
        print(f"✅ 同步完成!")
        print(f"📊 统计:")
        print(f"   - 新同步章节: {len(new_chapters)} 章")
        print(f"   - 总同步章节: {len(state['synced_chapters'])} 章")
    else:
        print("📝 没有新章节需要同步")
    
    print("")
    print("🔗 飞书表格地址:")
    print(f"   https://ecncmdjvm81e.feishu.cn/base/{app_token}")

if __name__ == "__main__":
    main()
PYTHON_EOF

echo "✅ 同步脚本创建完成"
echo ""

# 执行同步
echo "🚀 开始执行同步..."
python3 /tmp/sync_to_feishu.py "$CHAPTERS_DIR" "$SYNC_STATE" "$FEISHU_APP_TOKEN" "$FEISHU_TABLE_ID"

echo ""
echo "=== 同步流程完成 ==="
echo ""
echo "🎯 后续操作建议:"
echo "1. 安装飞书Python SDK: pip install lark-oapi"
echo "2. 配置飞书API密钥"
echo "3. 实现真正的API调用"
echo "4. 设置定时同步任务"
echo ""
echo "📁 相关信息:"
echo "   - 小说目录: $CHAPTERS_DIR"
echo "   - 状态文件: $SYNC_STATE"
echo "   - 飞书表格: https://ecncmdjvm81e.feishu.cn/base/$FEISHU_APP_TOKEN"
echo "   - 表格ID: $FEISHU_TABLE_ID"
echo ""
echo "⚠️  注意: 当前为模拟同步，需要实现真正的飞书API调用"