#!/bin/bash

# 生成 Tree-sitter 解析器
echo "=== 生成 Tree-sitter 解析器 ==="
# tree-sitter generate || { echo "❌ tree-sitter generate 失败"; exit 1; }

# 要解析的根目录数组
ROOT_DIRS=(
    # "/mnt/d/code/tinysoft/OfficeXml-dev/funcext/OfficeXml/autounit"
    # "/mnt/d/code/tinysoft/OfficeXml-dev/funcext/OfficeXml/openxml"
    # "/mnt/d/code/tinysoft/OfficeXml-dev/funcext/OfficeXml/utils"
    # "/mnt/d/code/tinysoft/OfficeXml-dev/funcext/OfficeXml/docx"
    # "/mnt/d/code/tinysoft/OfficeXml-dev/generator"
    # "/mnt/d/code/tinysoft/tsoffice/"
    # "/mnt/d/code/tinysoft/pdfconverter"
    # "/mnt/c/Programs/Tinysoft/TSLGen2/funcext/other"
    # "/mnt/c/Programs/Tinysoft/TSLGen2/funcext/tsword"
    # "/mnt/c/Programs/Tinysoft/TSLGen2/funcext/word2arr"
    # "/mnt/c/Programs/Tinysoft/TSLGen2/funcext/tsoffice"
    # "/mnt/c/Programs/Tinysoft/TSLGen2/funcext/OfficeXml-dev"
    # "/mnt/d/code/tinysoft/PdfConverter"
    "/mnt/c/Programs/Tinysoft/TSLGen2/funcext"
    # 可以添加更多目录
    # "/path/to/third/directory"
)

echo "=== 开始递归解析所有 .tsf 文件 ==="

# 错误标志
has_error=false

# 遍历所有根目录
for root_dir in "${ROOT_DIRS[@]}"; do
    echo "--- 处理目录: $root_dir"

    # 检查目录是否存在
    if [ ! -d "$root_dir" ]; then
        echo "❌ 目录不存在: $root_dir"
        has_error=true
        continue
    fi

    # 遍历当前目录下的所有 .tsf 文件
    while IFS= read -r -d '' file; do
        echo "--- 正在解析: $file"
        output=$(tree-sitter parse "$file" 2>&1)
        if echo "$output" | grep -q "ERROR\|MISSING"; then
            echo "❌ 语法错误在文件: $file"
            echo "$output"
            echo "--- 错误详情结束 ---"
            has_error=true
            # 如果希望遇到错误立即停止，取消注释下面这行
            break
        else
            echo "✓ 解析成功: $file"
        fi
    done < <(find "$root_dir" -type f -name "*.tsf" -print0)
done

# 检查是否有错误
if [ "$has_error" = true ]; then
    echo "❌ 解析过程中发现错误"
    exit 1
fi

echo "✅ 所有文件解析成功"
