#!/bin/bash

echo "🤖 手動 Android SDK 安裝腳本"
echo "==============================="

# 檢查 Android Studio 是否已安裝
if [ ! -d "/Applications/Android Studio.app" ]; then
    echo "❌ Android Studio 未安裝"
    exit 1
fi

# 設定 SDK 路徑
SDK_PATH="$HOME/Library/Android/sdk"
echo "📱 SDK 安裝路徑: $SDK_PATH"

# 創建 SDK 目錄
mkdir -p "$SDK_PATH"

# 設定環境變數
export ANDROID_HOME="$SDK_PATH"
export PATH="$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools"

echo "🔧 設定環境變數完成"

# 檢查 cmdline-tools 是否存在
CMDLINE_TOOLS="$SDK_PATH/cmdline-tools/latest/bin/sdkmanager"

if [ ! -f "$CMDLINE_TOOLS" ]; then
    echo "📥 下載 Android SDK Command Line Tools..."
    
    # 下載最新的 cmdline-tools
    TOOLS_URL="https://dl.google.com/android/repository/commandlinetools-mac-11076708_latest.zip"
    
    cd /tmp
    curl -o cmdline-tools.zip "$TOOLS_URL"
    
    if [ $? -eq 0 ]; then
        echo "✅ 下載成功，正在解壓..."
        unzip -q cmdline-tools.zip
        
        # 創建正確的目錄結構
        mkdir -p "$SDK_PATH/cmdline-tools"
        mv cmdline-tools "$SDK_PATH/cmdline-tools/latest"
        
        echo "✅ Command Line Tools 安裝完成"
    else
        echo "❌ 下載失敗，請檢查網路連線"
        exit 1
    fi
fi

# 更新 sdkmanager 路徑
CMDLINE_TOOLS="$SDK_PATH/cmdline-tools/latest/bin/sdkmanager"

if [ -f "$CMDLINE_TOOLS" ]; then
    echo "🔄 安裝基本 SDK 組件..."
    
    # 接受授權
    yes | "$CMDLINE_TOOLS" --licenses
    
    # 安裝基本組件
    "$CMDLINE_TOOLS" "platform-tools" "platforms;android-34" "build-tools;34.0.0" "emulator" "system-images;android-34;google_apis;arm64-v8a"
    
    echo "✅ 基本 SDK 組件安裝完成"
    
    # 創建模擬器
    echo "📱 創建 Android 模擬器..."
    
    AVDMANAGER="$SDK_PATH/cmdline-tools/latest/bin/avdmanager"
    
    if [ -f "$AVDMANAGER" ]; then
        # 創建 AVD
        echo "no" | "$AVDMANAGER" create avd -n "Pixel_4_API_34" -k "system-images;android-34;google_apis;arm64-v8a" -d "pixel_4"
        
        echo "✅ Android 模擬器創建完成: Pixel_4_API_34"
    fi
    
else
    echo "❌ SDK Manager 未找到"
    exit 1
fi

echo ""
echo "🎉 Android SDK 手動安裝完成！"
echo ""
echo "📋 驗證安裝："
echo "export ANDROID_HOME=\"$SDK_PATH\""
echo "export PATH=\"\$PATH:\$ANDROID_HOME/tools:\$ANDROID_HOME/platform-tools\""
echo ""
echo "執行驗證："
echo "./tools/environment/android/android_setup_verification.sh"