# auto_detect.conf - 自動判別設定
# 環境に応じて最適な設定を自動選択

# CLI binary detection (prefer hakorune, fallback to nyash if only that exists)
CLI_BIN="${NYASH_BIN_RESOLVED:-${NYASH_BIN:-./target/release/hakorune}}"
if [ ! -f "$CLI_BIN" ] && [ -f "./target/release/nyash" ]; then
    CLI_BIN="./target/release/nyash"
fi

# 自動判別ロジック
detect_optimal_config() {
    local config_type=""

    # 環境変数で明示指定があれば優先
    if [ -n "${SMOKES_FORCE_CONFIG:-}" ]; then
        config_type="$SMOKES_FORCE_CONFIG"
        echo "[INFO] Forced config: $config_type" >&2
    # CI環境検出
    elif [ -n "${CI:-}" ] || [ -n "${GITHUB_ACTIONS:-}" ] || [ -n "${GITLAB_CI:-}" ]; then
        config_type="llvm_static"
        echo "[INFO] CI environment detected, using LLVM static" >&2
    # LLVMビルド可能性チェック
    elif "$CLI_BIN" --version 2>/dev/null | grep -q "features.*llvm"; then
        config_type="llvm_static"
        echo "[INFO] LLVM available, using LLVM static" >&2
    # プラグインディレクトリ存在チェック
    elif [ -d "plugins" ] && find plugins -name "*.so" -type f | head -n1 | grep -q ".so"; then
        config_type="rust_vm_dynamic"
        echo "[INFO] Dynamic plugins found, using Rust VM dynamic" >&2
    # デフォルト
    else
        config_type="rust_vm_dynamic"
        echo "[INFO] Default configuration: Rust VM dynamic" >&2
    fi

    echo "$config_type"
}

# プロファイル別の自動調整
adjust_for_profile() {
    local profile="$1"
    local base_config="$2"

    case "$profile" in
        "quick")
            # 開発時は速度重視
            export NYASH_CLI_VERBOSE=1
            export SMOKES_FAST_FAIL=1
            export SMOKES_DEFAULT_TIMEOUT=15
            # 開発デフォルトは各テストが明示的に --dev を付与する想定に変更
            #（NYASH_DEV=1 の一括有効化はしない）
            # 安定化: Add adopt は明示ON時のみ。ここでは明示的にOFFを伝播させない。
            unset NYASH_DEV || true
            unset NYASH_OPERATOR_BOX_ADD_ADOPT || true
            unset NYASH_OPERATOR_BOX_STRINGIFY || true
            # Enable builder tail-based fallback for bare calls in quick profile
            export NYASH_BUILDER_TAIL_RESOLVE=1
            echo "[INFO] Quick profile: Speed optimized" >&2
            ;;
        "integration")
            # 統合テストは安定性重視
            export NYASH_CLI_VERBOSE=0
            export SMOKES_FAST_FAIL=0
            # EXE build/link を含むケース（例: Phase 87 LLVM exe line）は 60s を超えやすいので余裕を持たせる。
            export SMOKES_DEFAULT_TIMEOUT=120
            echo "[INFO] Integration profile: Stability optimized" >&2
            ;;
        "full")
            # 完全テストは網羅性重視
            export NYASH_CLI_VERBOSE=0
            export SMOKES_FAST_FAIL=0
            export SMOKES_DEFAULT_TIMEOUT=120
            export SMOKES_PARALLEL_TESTS=0
            echo "[INFO] Full profile: Comprehensive testing" >&2
            ;;
    esac
}

# 時刻ベースの自動調整
adjust_for_time() {
    local hour=$(date +%H)

    # 深夜・早朝は詳細テスト
    if [ "$hour" -ge 0 ] && [ "$hour" -lt 6 ]; then
        export SMOKES_EXTENDED_TESTS=1
        echo "[INFO] Night time: Extended testing enabled" >&2
    # 業務時間は高速テスト
    elif [ "$hour" -ge 9 ] && [ "$hour" -lt 18 ]; then
        export SMOKES_FAST_MODE=1
        echo "[INFO] Business hours: Fast mode enabled" >&2
    fi
}

# リソース使用量ベースの調整
adjust_for_resources() {
    # CPU使用率チェック（大まかな推定）
    local cpu_load
    if command -v nproc &> /dev/null; then
        local cpu_cores
        cpu_cores=$(nproc)
        if [ "$cpu_cores" -ge 8 ]; then
            export SMOKES_PARALLEL_TESTS=1
            echo "[INFO] High CPU cores detected: Parallel testing enabled" >&2
        fi
    fi

    # メモリチェック（Linux）
    if [ -f "/proc/meminfo" ]; then
        local mem_total_kb
        mem_total_kb=$(grep MemTotal /proc/meminfo | awk '{print $2}')
        local mem_total_gb=$((mem_total_kb / 1024 / 1024))

        if [ "$mem_total_gb" -ge 16 ]; then
            export SMOKES_MEMORY_INTENSIVE=1
            echo "[INFO] High memory detected: Memory-intensive tests enabled" >&2
        elif [ "$mem_total_gb" -le 4 ]; then
            export SMOKES_MEMORY_CONSERVATIVE=1
            echo "[INFO] Low memory detected: Conservative mode enabled" >&2
        fi
    fi
}

# メイン自動設定関数
auto_configure() {
    local profile="${1:-quick}"

    echo "[INFO] Auto-detecting optimal configuration..." >&2

    # 基本設定検出
    local optimal_config
    optimal_config=$(detect_optimal_config)

    # 設定ファイル読み込み
    local config_file="$(dirname "${BASH_SOURCE[0]}")/${optimal_config}.conf"
    if [ -f "$config_file" ]; then
        echo "[INFO] Loading config: $config_file" >&2
        source "$config_file"
    else
        echo "[WARN] Config file not found: $config_file" >&2
        echo "[INFO] Using minimal defaults" >&2
        export NYASH_DISABLE_PLUGINS=1
        export SMOKES_PLUGIN_MODE="auto"
    fi

    # プロファイル調整
    adjust_for_profile "$profile" "$optimal_config"

    # 時刻調整
    adjust_for_time

    # リソース調整
    adjust_for_resources

    echo "[INFO] Auto-configuration completed" >&2
    return 0
}

# 設定表示
show_auto_config() {
    cat << 'EOF'
===============================================
Auto-Detection Configuration
===============================================
EOF

    echo "Detected Config: $(detect_optimal_config)"
    echo "Current Profile: ${SMOKES_CURRENT_PROFILE:-unknown}"
    echo "Plugin Mode: ${SMOKES_PLUGIN_MODE:-auto}"
    echo "Backend: ${NYASH_BACKEND:-default}"
    echo "Fast Fail: ${SMOKES_FAST_FAIL:-0}"
    echo "Parallel Tests: ${SMOKES_PARALLEL_TESTS:-0}"
    echo "Default Timeout: ${SMOKES_DEFAULT_TIMEOUT:-30}s"
    echo ""

    # 環境情報
    echo "Environment:"
    echo "  CI: ${CI:-false}"
    echo "  CPU Cores: $(nproc 2>/dev/null || echo 'unknown')"
    echo "  Current Hour: $(date +%H)"

    echo ""
    echo "==============================================="
}

# 使用例
# source configs/auto_detect.conf
# auto_configure "quick"
# show_auto_config
