$ErrorActionPreference = "Stop"

$repo = "StitcyYT/Complex-X-"
$installDir = "$env:LOCALAPPDATA\Complexx"
$desktopDir = [Environment]::GetFolderPath("Desktop")
$exePath = "$installDir\raycaster.exe"

if (Test-Path $exePath) {
    Add-Type -AssemblyName System.Windows.Forms
    $result = [System.Windows.Forms.MessageBox]::Show(
        "Do you want to update to the latest version?",
        "Complexx Raycaster",
        [System.Windows.Forms.MessageBoxButtons]::YesNo,
        [System.Windows.Forms.MessageBoxIcon]::Question
    )
    if ($result -ne [System.Windows.Forms.DialogResult]::Yes) {
        exit 0
    }
}

Write-Host "Downloading Complexx Raycaster from GitHub..."

$release = Invoke-RestMethod -Uri "https://api.github.com/repos/$repo/releases/latest" -UseBasicParsing
$asset = $release.assets | Where-Object { $_.name -like "*.zip" } | Select-Object -First 1
if (-not $asset) {
    [System.Windows.Forms.MessageBox]::Show(
        "No release found on GitHub.",
        "Complexx Raycaster",
        [System.Windows.Forms.MessageBoxButtons]::OK,
        [System.Windows.Forms.MessageBoxIcon]::Error
    )
    exit 1
}

$zipPath = "$env:TEMP\complexx_download.zip"
Invoke-WebRequest -Uri $asset.browser_download_url -OutFile $zipPath -UseBasicParsing

Write-Host "Installing to $installDir ..."
if (Test-Path $installDir) { Remove-Item $installDir -Recurse -Force }
New-Item -ItemType Directory -Path $installDir -Force | Out-Null

Expand-Archive -Path $zipPath -DestinationPath $installDir -Force
Remove-Item $zipPath -Force

if (-not (Test-Path $exePath)) {
    [System.Windows.Forms.MessageBox]::Show(
        "Install failed: raycaster.exe not found.",
        "Complexx Raycaster",
        [System.Windows.Forms.MessageBoxButtons]::OK,
        [System.Windows.Forms.MessageBoxIcon]::Error
    )
    exit 1
}

Copy-Item $exePath "$desktopDir\Complexx Raycaster.exe" -Force

[System.Windows.Forms.MessageBox]::Show(
    "Complexx Raycaster is ready! Check your Desktop.",
    "Complexx Raycaster",
    [System.Windows.Forms.MessageBoxButtons]::OK,
    [System.Windows.Forms.MessageBoxIcon]::Information
)
