#!/bin/bash
# Feature依赖关系检查脚本

set -e

echo "🔍 检查Feature依赖关系..."

# 获取所有feature分支
FEATURE_BRANCHES=$(git branch | grep -E '^  [0-9]{3}-' | sed 's/^  //')
CURRENT_BRANCH=$(git branch --show-current)

# 定义Feature依赖关系 (兼容旧版bash)
get_dependencies() {
    case "$1" in
        "001-specManager-perp")
            echo ""
            ;;
        "002-credential-manager")
            echo ""
            ;;
        "003-delta-50-80")
            echo "001-specManager-perp,002-credential-manager"
            ;;
        *)
            echo ""
            ;;
    esac
}

# 检查函数
check_dependencies() {
    local feature=$1
    local deps=$(get_dependencies "$feature")

    echo "📋 检查 $feature 的依赖..."

    if [[ -z "$deps" ]]; then
        echo "  ✅ 无依赖项"
        return 0
    fi

    IFS=',' read -ra DEP_ARRAY <<< "$deps"
    local missing_deps=()

    for dep in "${DEP_ARRAY[@]}"; do
        # 检查依赖的spec是否存在
        if [[ ! -d "specs/$dep" ]]; then
            missing_deps+=("$dep (spec缺失)")
            continue
        fi

        # 检查依赖的feature是否已合并到main
        git checkout main >/dev/null 2>&1
        if [[ ! -d "specs/$dep" ]]; then
            missing_deps+=("$dep (未合并到main)")
        fi
        git checkout "$CURRENT_BRANCH" >/dev/null 2>&1
    done

    if [[ ${#missing_deps[@]} -eq 0 ]]; then
        echo "  ✅ 所有依赖项满足"
    else
        echo "  ❌ 缺失依赖项:"
        for missing in "${missing_deps[@]}"; do
            echo "    - $missing"
        done
        return 1
    fi
}

# 检查共享组件冲突
check_shared_components() {
    echo "🔧 检查共享组件冲突..."

    local conflicts_found=0

    # 检查AccountManager
    if [[ -f "src/modules/account/AccountManager.ts" ]]; then
        local account_features=$(grep -l "AccountManager" specs/*/tasks.md 2>/dev/null | wc -l)
        if [[ $account_features -gt 1 ]]; then
            echo "  ⚠️  AccountManager被多个feature使用: $account_features个"
            conflicts_found=1
        fi
    fi

    # 检查PriceManager
    if [[ -f "src/modules/trading/PriceManager.ts" ]]; then
        local price_features=$(grep -l "PriceManager" specs/*/tasks.md 2>/dev/null | wc -l)
        if [[ $price_features -gt 1 ]]; then
            echo "  ⚠️  PriceManager被多个feature使用: $price_features个"
            conflicts_found=1
        fi
    fi

    if [[ $conflicts_found -eq 0 ]]; then
        echo "  ✅ 无共享组件冲突"
    fi

    return $conflicts_found
}

# 主检查逻辑
main() {
    local has_issues=0

    echo "📊 Feature依赖关系检查报告"
    echo "================================"

    for feature in $FEATURE_BRANCHES; do
        if ! check_dependencies "$feature"; then
            has_issues=1
        fi
        echo ""
    done

    if ! check_shared_components; then
        has_issues=1
    fi

    echo "================================"
    if [[ $has_issues -eq 0 ]]; then
        echo "✅ 所有Feature依赖关系检查通过"
    else
        echo "❌ 发现依赖关系问题，请解决后再继续"
        exit 1
    fi
}

main "$@"