#requires -Version 5.0
# AyaanScript+ Windows installer
# 1. Installs rustup (MSVC toolchain) if Rust isn't present
# 2. If Rust IS present but default is GNU, switches to MSVC (GNU often has
#    a broken mingw bundle on Windows - windows-sys fails to compile)
# 3. Runs `cargo install ayaan --force` with build-speed profile overrides

$ErrorActionPreference = 'Stop'

function Write-Banner {
    Write-Host ""
    Write-Host "+============================================+" -ForegroundColor Cyan
    Write-Host "|         AyaanScript+ Windows Installer     |" -ForegroundColor Yellow
    Write-Host "+============================================+" -ForegroundColor Cyan
    Write-Host ""
}

function Test-Command($cmd) {
    $null = Get-Command $cmd -ErrorAction SilentlyContinue
    $?
}

function Check-Existing {
    Write-Host "[1/5] Checking for existing AyaanScript+ install..." -ForegroundColor Cyan
    $cargoBin = Join-Path $env:USERPROFILE ".cargo\bin"
    $ayaanExe = Join-Path $cargoBin "ayaan.exe"
    if (Test-Path $ayaanExe) {
        $existingVer = ""
        try {
            $existingVer = (& $ayaanExe --version 2>&1) -as [string]
        } catch { $existingVer = "(unknown)" }
        Write-Host "      WARNING: existing install found: $($existingVer.Trim())" -ForegroundColor Yellow
        Write-Host "      It will be overwritten with the latest from crates.io." -ForegroundColor Yellow
    } else {
        Write-Host "      No existing install found." -ForegroundColor Green
    }
}

function Install-Rust {
    Write-Host ""
    Write-Host "[2/5] Checking for Rust toolchain..." -ForegroundColor Cyan
    if (Test-Command "cargo") {
        $ver = (& cargo --version) 2>&1
        Write-Host "      Found: $ver" -ForegroundColor Green
        return
    }

    Write-Host "      Rust not found. Downloading rustup-init.exe..." -ForegroundColor Yellow
    $rustupUrl = "https://win.rustup.rs/x86_64"
    $tmp = Join-Path $env:TEMP "rustup-init.exe"
    Invoke-WebRequest -Uri $rustupUrl -OutFile $tmp -UseBasicParsing

    Write-Host "      Installing Rust (MSVC toolchain)..." -ForegroundColor Yellow
    & $tmp -y --default-toolchain stable --profile minimal | Out-Null
    Remove-Item $tmp -ErrorAction SilentlyContinue

    $cargoBin = Join-Path $env:USERPROFILE ".cargo\bin"
    if (Test-Path $cargoBin) {
        $env:Path = "$cargoBin;$env:Path"
    }

    if (-not (Test-Command "cargo")) {
        Write-Host "      ERROR: Rust install failed. Restart your shell and re-run." -ForegroundColor Red
        exit 1
    }
    Write-Host "      Rust installed." -ForegroundColor Green
}

# Ensure the active toolchain is MSVC. If user has rustup with GNU default
# (the common broken-mingw state), switch to MSVC. Install MSVC toolchain
# if it isn't present.
function Ensure-MSVC {
    Write-Host ""
    Write-Host "[3/5] Verifying MSVC toolchain..." -ForegroundColor Cyan
    if (-not (Test-Command "rustup")) {
        Write-Host "      WARNING: rustup not on PATH - skipping toolchain check." -ForegroundColor Yellow
        return
    }

    $active = (& rustup show active-toolchain 2>&1) -as [string]
    if ($active -match "gnu") {
        Write-Host "      Default toolchain is GNU; switching to MSVC..." -ForegroundColor Yellow
        # Check if MSVC is installed
        $list = (& rustup toolchain list 2>&1) -as [string]
        if ($list -notmatch "x86_64-pc-windows-msvc") {
            Write-Host "      Installing stable-x86_64-pc-windows-msvc..." -ForegroundColor Yellow
            & rustup toolchain install stable-x86_64-pc-windows-msvc --profile minimal
            if ($LASTEXITCODE -ne 0) {
                Write-Host "      ERROR: failed to install MSVC toolchain." -ForegroundColor Red
                Write-Host "      You may need Visual Studio Build Tools:" -ForegroundColor Yellow
                Write-Host "      https://visualstudio.microsoft.com/visual-cpp-build-tools/" -ForegroundColor Yellow
                exit 1
            }
        }
        & rustup default stable-x86_64-pc-windows-msvc | Out-Null
        Write-Host "      Default toolchain set to stable-x86_64-pc-windows-msvc." -ForegroundColor Green
    } else {
        Write-Host "      Active toolchain: $($active.Trim())" -ForegroundColor Green
    }
}

function Install-AyaanScript {
    Write-Host ""
    Write-Host "[4/5] Installing AyaanScript+ via cargo..." -ForegroundColor Cyan
    Write-Host "      (compile + link takes 3-10 minutes - this is normal)" -ForegroundColor Gray

    # Build-speed profile overrides - apply without modifying crates.io Cargo.toml
    $env:CARGO_PROFILE_RELEASE_OPT_LEVEL    = "1"
    $env:CARGO_PROFILE_RELEASE_CODEGEN_UNITS = "256"
    $env:CARGO_PROFILE_RELEASE_LTO          = "false"
    $env:CARGO_PROFILE_RELEASE_STRIP        = "debuginfo"
    $env:CARGO_INCREMENTAL                  = "0"

    Write-Host "      Running: cargo install ayaan --force" -ForegroundColor Gray
    Write-Host ""
    & cargo install ayaan --force
    if ($LASTEXITCODE -ne 0) {
        Write-Host ""
        Write-Host "      ERROR: cargo install failed." -ForegroundColor Red
        Write-Host "      If the error mentions 'link.exe' or 'cl.exe' not found, install:" -ForegroundColor Yellow
        Write-Host "        https://visualstudio.microsoft.com/visual-cpp-build-tools/" -ForegroundColor Yellow
        Write-Host "      (pick the 'Desktop development with C++' workload)" -ForegroundColor Yellow
        exit 1
    }
    Write-Host ""
    Write-Host "      Installed." -ForegroundColor Green
}

function Verify-Install {
    Write-Host ""
    Write-Host "[5/5] Verifying..." -ForegroundColor Cyan
    $cargoBin = Join-Path $env:USERPROFILE ".cargo\bin"
    $ayaanExe = Join-Path $cargoBin "ayaan.exe"
    $aspkgExe = Join-Path $cargoBin "aspkg.exe"
    if ((Test-Path $ayaanExe) -and (Test-Path $aspkgExe)) {
        Write-Host "      ayaan.exe + aspkg.exe found in $cargoBin" -ForegroundColor Green
    } else {
        Write-Host "      WARNING: binaries not found at expected path." -ForegroundColor Yellow
    }

    $userPath = [Environment]::GetEnvironmentVariable("Path", "User")
    if ($userPath -notlike "*$cargoBin*") {
        Write-Host "      Adding $cargoBin to User PATH..." -ForegroundColor Yellow
        [Environment]::SetEnvironmentVariable("Path", "$cargoBin;$userPath", "User")
        Write-Host "      PATH updated. Open a NEW terminal to pick it up." -ForegroundColor Yellow
    } else {
        Write-Host "      PATH already includes cargo bin." -ForegroundColor Green
    }
}

function Show-Done {
    Write-Host ""
    Write-Host "+============================================+" -ForegroundColor Green
    Write-Host "|        Installation Complete!              |" -ForegroundColor Green
    Write-Host "+============================================+" -ForegroundColor Green
    Write-Host ""
    Write-Host "Try it out (open a NEW PowerShell window first):" -ForegroundColor Cyan
    Write-Host "    ayaan                       " -NoNewline; Write-Host "(starts the REPL)" -ForegroundColor Gray
    Write-Host "    ayaan myfile.ayaan          " -NoNewline; Write-Host "(runs a script)" -ForegroundColor Gray
    Write-Host "    aspkg help                  " -NoNewline; Write-Host "(package manager)" -ForegroundColor Gray
    Write-Host ""
}

Write-Banner
Check-Existing
Install-Rust
Ensure-MSVC
Install-AyaanScript
Verify-Install
Show-Done
