# Ilum CLI Installer for Windows (PowerShell)
# Usage: irm https://get.ilum.cloud/cli/windows | iex
#   or:  $env:ILUM_VERSION = "0.2.0"; .\install.ps1

param(
    [string]$Version = ""
)

$ErrorActionPreference = "Stop"

$Repo = "ilum-cloud/ilum-cli"
$InstallDir = Join-Path $env:LOCALAPPDATA "Programs\ilum"

# ---------------------------------------------------------------------------
# Output helpers
# ---------------------------------------------------------------------------

function Write-Info  { param([string]$Msg) Write-Host "==> $Msg" -ForegroundColor Blue }
function Write-Ok    { param([string]$Msg) Write-Host "==> $Msg" -ForegroundColor Green }
function Write-Warn  { param([string]$Msg) Write-Host "WARNING: $Msg" -ForegroundColor Yellow }
function Write-Err   { param([string]$Msg) Write-Host "ERROR: $Msg" -ForegroundColor Red }

function Stop-WithError {
    param([string]$Msg)
    Write-Err $Msg
    exit 1
}

# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

function Get-LatestVersion {
    if ($Version) {
        Write-Info "Using version from -Version parameter: $Version"
        return $Version
    }
    if ($env:ILUM_VERSION) {
        Write-Info "Using pinned version: $env:ILUM_VERSION"
        return $env:ILUM_VERSION
    }

    Write-Info "Querying latest release from GitHub..."
    try {
        $apiBase = if ($env:ILUM_GITHUB_API) { $env:ILUM_GITHUB_API } else { "https://api.github.com" }
        $release = Invoke-RestMethod -Uri "$apiBase/repos/$Repo/releases/latest"
        $tag = $release.tag_name
        $version = $tag -replace '^cli-v', ''
        if (-not $version) {
            Stop-WithError "Could not parse version from tag: $tag"
        }
        Write-Info "Latest version: $version"
        return $version
    }
    catch {
        Stop-WithError "Could not determine latest version. Set `$env:ILUM_VERSION manually."
    }
}

function Get-Platform {
    $arch = $env:PROCESSOR_ARCHITECTURE
    if ($arch -eq "AMD64") {
        return "windows-amd64"
    }
    elseif ($arch -eq "ARM64") {
        return "windows-arm64"
    }
    else {
        Stop-WithError "Unsupported architecture: $arch"
    }
}

# ---------------------------------------------------------------------------
# Installation strategies (tiered fallback)
# ---------------------------------------------------------------------------

function Try-WingetInstall {
    param([string]$Version)
    if (-not (Get-Command winget -ErrorAction SilentlyContinue)) {
        return $false
    }
    Write-Info "Installing via winget..."
    try {
        winget install --id ilum-cloud.ilum -e --version $Version `
            --accept-source-agreements --accept-package-agreements 2>&1 | Out-Null
        if ($LASTEXITCODE -eq 0) { return $true }
    }
    catch { }
    Write-Warn "winget install failed, trying next method..."
    return $false
}

function Try-PipInstall {
    param([string]$Version)
    if (-not (Get-Command pip -ErrorAction SilentlyContinue)) {
        return $false
    }
    Write-Info "Installing via pip..."
    try {
        pip install "ilum==$Version" 2>&1 | Out-Null
        if ($LASTEXITCODE -eq 0) { return $true }
    }
    catch { }
    Write-Warn "pip install failed, trying next method..."
    return $false
}

function Install-Binary {
    param([string]$Version, [string]$Platform)

    $archive = "ilum-$Platform.zip"
    $dlBase  = if ($env:ILUM_DOWNLOAD_BASE) { $env:ILUM_DOWNLOAD_BASE } else { "https://github.com" }
    $baseUrl = "$dlBase/$Repo/releases/download/cli-v$Version"
    $tmpDir  = Join-Path $env:TEMP "ilum-install-$(Get-Random)"

    New-Item -ItemType Directory -Path $tmpDir -Force | Out-Null

    try {
        Write-Info "Downloading $archive..."
        Invoke-WebRequest -Uri "$baseUrl/$archive" -OutFile (Join-Path $tmpDir $archive)
        Invoke-WebRequest -Uri "$baseUrl/SHA256SUMS" -OutFile (Join-Path $tmpDir "SHA256SUMS")

        # Verify checksum
        Write-Info "Verifying checksum..."
        $expectedLine = Get-Content (Join-Path $tmpDir "SHA256SUMS") |
            Where-Object { $_ -match $archive }
        if (-not $expectedLine) {
            Stop-WithError "Archive not found in SHA256SUMS"
        }
        $expectedHash = ($expectedLine -split '\s+')[0]
        $actualHash = (Get-FileHash -Path (Join-Path $tmpDir $archive) -Algorithm SHA256).Hash
        if ($actualHash -ne $expectedHash) {
            Stop-WithError "Checksum verification failed! Expected $expectedHash, got $actualHash"
        }
        Write-Ok "Checksum OK"

        # Extract
        Expand-Archive -Path (Join-Path $tmpDir $archive) -DestinationPath $tmpDir -Force

        # Install binary
        if (-not (Test-Path $InstallDir)) {
            New-Item -ItemType Directory -Path $InstallDir -Force | Out-Null
        }
        $target = Join-Path $InstallDir "ilum.exe"
        Move-Item -Path (Join-Path $tmpDir "ilum.exe") -Destination $target -Force

        Write-Ok "Installed ilum to $target"

        # Check PATH
        $userPath = [Environment]::GetEnvironmentVariable("PATH", "User")
        if ($userPath -notlike "*$InstallDir*") {
            Write-Info "Adding $InstallDir to your PATH..."
            [Environment]::SetEnvironmentVariable(
                "PATH",
                "$InstallDir;$userPath",
                "User"
            )
            Write-Ok "Added $InstallDir to user PATH. Restart your terminal to use 'ilum'."
        }
    }
    finally {
        Remove-Item -Recurse -Force $tmpDir -ErrorAction SilentlyContinue
    }
}

# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

function Main {
    Write-Info "Ilum CLI Installer (Windows)"
    Write-Host ""

    $platform = Get-Platform
    Write-Info "Detected platform: $platform"
    $version = Get-LatestVersion
    Write-Host ""

    # Tiered fallback: winget -> pip -> binary download
    if (Try-WingetInstall -Version $version) {
        Write-Ok "Ilum CLI installed via winget"
        return
    }

    if (Try-PipInstall -Version $version) {
        Write-Ok "Ilum CLI $version installed via pip"
        return
    }

    Write-Info "Falling back to binary download..."
    Install-Binary -Version $version -Platform $platform

    Write-Host ""
    Write-Ok "Ilum CLI $version installed successfully!"
    Write-Info "Run 'ilum init' to get started."

    # Verify installation
    if (Get-Command ilum -ErrorAction SilentlyContinue) {
        ilum --version
    }
    else {
        Write-Warn "ilum not found on PATH. You may need to restart your terminal."
    }
}

Main
