#!/usr/bin/env python3
"""
为学习文档添加导航链接的脚本
"""

import os
import re
from pathlib import Path

# 定义章节结构和导航顺序
CHAPTER_STRUCTURE = {
    "00-overview": [
        "environment-setup.md",
        "project-overview.md", 
        "learning-guide.md"
    ],
    "01-python-basics": [
        "syntax-fundamentals.md",
        "data-structures.md",
        "functions-modules.md",
        "oop-basics.md",
        "exception-handling.md",
        "file-io.md",
        "builtin-libraries.md"
    ],
    "02-development-environment": [
        "python-installation.md",
        "ide-configuration.md",
        "virtual-environments.md",
        "package-management.md",
        "git-basics.md",
        "debugging-tools.md"
    ],
    "03-computer-fundamentals": [
        "network-fundamentals.md",
        "operating-systems.md",
        "database-data-structures.md",
        "encoding-and-charset.md",
        "socket-programming.md",
        "security-basics.md"
    ],
    "04-software-engineering": [
        "project-organization.md",
        "modular-design.md",
        "pep8-standards.md",
        "patterns-in-chatroom.md"
    ],
    "05-chatroom-basics": [
        "requirements-analysis.md",
        "socket-basics.md",
        "system-architecture.md",
        "message-protocol.md"
    ],
    "06-socket-programming": [
        "network-concepts.md",
        "tcp-basics.md",
        "socket-api.md",
        "simple-client-server.md"
    ],
    "07-simple-chat": [
        "protocol-design.md",
        "message-handling.md",
        "threading-basics.md",
        "error-handling.md"
    ],
    "08-database-user-system": [
        "sqlite-basics.md",
        "database-design.md",
        "user-authentication.md",
        "data-models.md"
    ],
    "09-multi-user-chat": [
        "group-management.md",
        "message-routing.md",
        "concurrent-handling.md",
        "state-management.md",
        "user-connection-pool.md"
    ],
    "10-file-transfer": [
        "file-protocol.md",
        "chunked-transfer.md",
        "progress-tracking.md",
        "security-validation.md"
    ],
    "11-ai-integration": [
        "api-integration.md",
        "glm-4-flash-features.md",
        "context-management.md",
        "async-processing.md"
    ],
    "12-user-interface": [
        "tui-concepts.md",
        "textual-framework.md",
        "component-design.md",
        "theme-system.md"
    ],
    "13-admin-system": [
        "permission-model.md",
        "command-system.md",
        "crud-operations.md",
        "security-measures.md"
    ],
    "14-logging-error-handling": [
        "loguru-system.md",
        "error-strategies.md",
        "debugging-techniques.md",
        "monitoring-diagnostics.md"
    ],
    "15-testing-quality": [
        "tdd-practices.md",
        "pytest-framework.md",
        "unit-testing.md",
        "integration-testing.md",
        "test-coverage.md",
        "mock-testing.md"
    ],
    "16-optimization-deployment": [
        "performance-optimization.md",
        "monitoring-operations.md",
        "containerization-deployment.md",
        "cicd-automation.md",
        "deployment-strategies.md"
    ],
    "17-advanced-project-practice": [
        "feature-planning-analysis.md",
        "performance-bottleneck-identification.md",
        "troubleshooting-methodology.md"
    ],
    "18-advanced-project-practice": [
        "feature-optimization.md",
        "code-refactoring.md",
        "tuning-case.md",
        "troubleshooting-production.md",
        "user-feedback.md",
        "contributing-guide.md"
    ]
}

def get_chapter_title(chapter_key):
    """获取章节标题"""
    titles = {
        "00-overview": "第0章：学习准备",
        "01-python-basics": "第1章：Python基础",
        "02-development-environment": "第2章：开发环境",
        "03-computer-fundamentals": "第3章：计算机基础",
        "04-software-engineering": "第4章：软件工程",
        "05-chatroom-basics": "第5章：项目入门",
        "06-socket-programming": "第6章：网络编程",
        "07-simple-chat": "第7章：简单聊天",
        "08-database-user-system": "第8章：数据库系统",
        "09-multi-user-chat": "第9章：多人聊天",
        "10-file-transfer": "第10章：文件传输",
        "11-ai-integration": "第11章：AI集成",
        "12-user-interface": "第12章：用户界面",
        "13-admin-system": "第13章：管理员系统",
        "14-logging-error-handling": "第14章：日志处理",
        "15-testing-quality": "第15章：测试开发",
        "16-optimization-deployment": "第16章：优化部署",
        "17-advanced-project-practice": "第17章：高级实践",
        "18-advanced-project-practice": "第18章：进阶实战"
    }
    return titles.get(chapter_key, chapter_key)

def get_file_title(filename):
    """从文件名获取标题"""
    # 移除.md扩展名并转换为标题
    name = filename.replace('.md', '')
    # 简单的标题映射（实际应该从文件内容中提取）
    return name.replace('-', ' ').title()

def find_navigation_info(chapter_key, filename):
    """查找导航信息"""
    files = CHAPTER_STRUCTURE.get(chapter_key, [])
    if filename not in files:
        return None, None, None
    
    current_index = files.index(filename)
    
    # 上一个文件
    prev_file = None
    prev_title = None
    if current_index > 0:
        prev_file = files[current_index - 1]
        prev_title = get_file_title(prev_file)
    
    # 下一个文件
    next_file = None
    next_title = None
    if current_index < len(files) - 1:
        next_file = files[current_index + 1]
        next_title = get_file_title(next_file)
    
    return prev_file, prev_title, next_file, next_title

def generate_navigation_section(chapter_key, filename):
    """生成导航部分"""
    prev_file, prev_title, next_file, next_title = find_navigation_info(chapter_key, filename)
    
    if not prev_file and not next_file:
        return ""
    
    navigation = "\n## 📖 导航\n\n"
    
    if prev_file:
        navigation += f"⬅️ **上一节：** [{prev_title}]({prev_file})\n\n"
    
    if next_file:
        navigation += f"➡️ **下一节：** [{next_title}]({next_file})\n\n"
    
    # 添加章节导航
    chapter_title = get_chapter_title(chapter_key)
    navigation += f"📚 **返回：** [{chapter_title}](README.md)\n\n"
    navigation += f"🏠 **主页：** [学习路径总览](../README.md)\n\n"
    
    return navigation

def add_navigation_to_file(file_path, chapter_key, filename):
    """为文件添加导航链接"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 检查是否已经有导航部分
        if "## 📖 导航" in content or "## 📚 下一步" in content:
            print(f"跳过 {file_path}：已有导航链接")
            return False
        
        # 生成导航部分
        navigation = generate_navigation_section(chapter_key, filename)
        
        if not navigation:
            return False
        
        # 在文件末尾添加导航（在最后的分隔线之前）
        if content.endswith('\n'):
            content = content.rstrip('\n')
        
        # 查找最后的分隔线
        lines = content.split('\n')
        insert_index = len(lines)
        
        # 从后往前查找合适的插入位置
        for i in range(len(lines) - 1, -1, -1):
            line = lines[i].strip()
            if line.startswith('---') or line.startswith('*本') or line.startswith('**'):
                insert_index = i
                break
        
        # 插入导航部分
        lines.insert(insert_index, navigation.rstrip())
        
        # 写回文件
        new_content = '\n'.join(lines) + '\n'
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(new_content)
        
        print(f"✅ 已为 {file_path} 添加导航链接")
        return True
        
    except Exception as e:
        print(f"❌ 处理 {file_path} 时出错：{e}")
        return False

def main():
    """主函数"""
    docs_dir = Path("docs/learning-v02")
    
    if not docs_dir.exists():
        print(f"错误：文档目录 {docs_dir} 不存在")
        return
    
    total_processed = 0
    total_updated = 0
    
    for chapter_key, files in CHAPTER_STRUCTURE.items():
        chapter_dir = docs_dir / chapter_key
        
        if not chapter_dir.exists():
            print(f"警告：章节目录 {chapter_dir} 不存在")
            continue
        
        print(f"\n处理章节：{get_chapter_title(chapter_key)}")
        
        for filename in files:
            file_path = chapter_dir / filename
            
            if file_path.exists():
                total_processed += 1
                if add_navigation_to_file(file_path, chapter_key, filename):
                    total_updated += 1
            else:
                print(f"警告：文件 {file_path} 不存在")
    
    print(f"\n📊 处理完成：")
    print(f"   总文件数：{total_processed}")
    print(f"   已更新：{total_updated}")
    print(f"   跳过：{total_processed - total_updated}")

if __name__ == "__main__":
    main()
