# Check if running as Admin
If (-Not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
    Write-Error "Run this script as Administrator!"
    exit
}

# Function to get the latest stable Flutter SDK URL
Function Get-LatestFlutterSdkUrl {
    $releasesUrl = "https://storage.googleapis.com/flutter_infra_release/releases/releases_windows.json"
    Write-Output "Fetching latest Flutter SDK releases information..."
    $response = Invoke-WebRequest -Uri $releasesUrl -UseBasicParsing | ConvertFrom-Json

    # Get the base URL and the latest stable release archive path
    $baseUrl = $response.base_url
    $latestStable = $response.releases | Where-Object { $_.channel -eq "stable" } | Select-Object -First 1

    If ($null -eq $latestStable) {
        Write-Error "No stable Flutter SDK release found."
        exit
    }

    $sdkArchivePath = $latestStable.archive
    $sdkDownloadUrl = "$baseUrl/$sdkArchivePath"
    return $sdkDownloadUrl
}

# Get the latest Flutter SDK URL
$flutterSdkUrl = Get-LatestFlutterSdkUrl

# User input for Flutter SDK destination folder
$flutterDestination = Read-Host "Enter the folder where Flutter SDK should be extracted (e.g., C:\flutter)"

# Download Flutter SDK
Write-Output "Downloading Flutter SDK from $flutterSdkUrl..."
$flutterZip = "$env:TEMP\flutter_sdk.zip"
Invoke-WebRequest -Uri $flutterSdkUrl -OutFile $flutterZip

# Extract Flutter SDK
Write-Output "Extracting Flutter SDK to $flutterDestination..."
Expand-Archive -Path $flutterZip -DestinationPath $flutterDestination -Force

# Set Environment Variables for Flutter
Write-Output "Setting Environment Variables for Flutter..."
$flutterBinPath = "$flutterDestination\flutter\bin"
[System.Environment]::SetEnvironmentVariable("Path", "$env:Path;$flutterBinPath", [System.EnvironmentVariableTarget]::Machine)

# Android Studio Installer URL
$androidStudioUrl = "https://redirector.gvt1.com/edgedl/android/studio/install/2024.1.2.12/android-studio-2024.1.2.12-windows.exe"

# Download Android Studio
Write-Output "Downloading Android Studio..."
$androidStudioInstaller = "$env:TEMP\android_studio.exe"
Invoke-WebRequest -Uri $androidStudioUrl -OutFile $androidStudioInstaller

# Install Android Studio
Write-Output "Installing Android Studio silently..."
Start-Process -FilePath $androidStudioInstaller -ArgumentList "/S" -Wait

Write-Output "Installation complete. Please restart your system to apply changes."