# TypeDialog Installation Script for Windows
# Installs typedialog binaries and configuration

param(
    [string]$InstallDir = "$env:USERPROFILE\.local\bin",
    [string]$ConfigDir = "$env:USERPROFILE\.config\typedialog",
    [string]$Version = "latest"
)

$ErrorActionPreference = "Stop"
$GitHubRepo = "anthropics/typedialog"

# Function: Print info message
function Write-Info {
    param([string]$Message)
    Write-Host "[INFO] $Message" -ForegroundColor Cyan
}

# Function: Print error message
function Write-Err {
    param([string]$Message)
    Write-Host "[ERROR] $Message" -ForegroundColor Red
}

# Function: Print success message
function Write-Success {
    param([string]$Message)
    Write-Host "[✓] $Message" -ForegroundColor Green
}

# Function: Detect platform
function Get-Platform {
    $arch = $env:PROCESSOR_ARCHITECTURE

    switch ($arch) {
        "AMD64" { return "windows-x86_64" }
        "ARM64" { return "windows-aarch64" }
        default {
            Write-Err "Unsupported architecture: $arch"
            exit 1
        }
    }
}

# Function: Create directories
function New-DirectoryStructure {
    param([string]$InstallDir, [string]$ConfigDir)

    Write-Info "Creating directories..."

    if (-not (Test-Path $InstallDir)) {
        New-Item -ItemType Directory -Path $InstallDir -Force | Out-Null
    }

    if (-not (Test-Path $ConfigDir)) {
        New-Item -ItemType Directory -Path $ConfigDir -Force | Out-Null
    }

    Write-Success "Directories created"
}

# Function: Download release
function Get-Release {
    param([string]$Platform, [string]$Version)

    $DownloadUrl = "https://github.com/$GitHubRepo/releases/download/$Version/typedialog-$Platform.zip"
    $TempFile = [System.IO.Path]::GetTempFileName()

    Write-Info "Downloading: $DownloadUrl"

    try {
        Invoke-WebRequest -Uri $DownloadUrl -OutFile $TempFile -ErrorAction Stop
        Write-Success "Download complete"
        return $TempFile
    }
    catch {
        Write-Err "Download failed: $_"
        exit 1
    }
}

# Function: Extract archive
function Expand-Release {
    param([string]$Archive)

    $ExtractDir = New-Item -ItemType Directory -Path (Join-Path $env:TEMP "typedialog-extract") -Force | Select-Object -ExpandProperty FullName

    Write-Info "Extracting archive..."

    try {
        Expand-Archive -Path $Archive -DestinationPath $ExtractDir -Force
        Write-Success "Extraction complete"
        return $ExtractDir
    }
    catch {
        Write-Err "Extraction failed: $_"
        exit 1
    }
}

# Function: Install binaries
function Install-Binaries {
    param([string]$ExtractDir, [string]$InstallDir)

    $Binaries = @("typedialog.exe", "typedialog-tui.exe", "typedialog-web.exe", "typedialog-ai.exe", "typedialog-ag.exe", "typedialog-prov-gen.exe")
    $BinDir = Join-Path $ExtractDir "bin"

    foreach ($binary in $Binaries) {
        $BinaryPath = Join-Path $BinDir $binary

        if (Test-Path $BinaryPath) {
            Copy-Item -Path $BinaryPath -Destination $InstallDir -Force
            Write-Success "Installed: $binary"
        }
    }
}

# Function: Install configurations
function Install-Configs {
    param([string]$ExtractDir, [string]$ConfigDir)

    $ConfigSrc = Join-Path $ExtractDir "config"

    if (Test-Path $ConfigSrc) {
        Copy-Item -Path "$ConfigSrc\*" -Destination $ConfigDir -Recurse -Force
        Write-Success "Configurations installed"
    }
}

# Function: Update PATH
function Update-Path {
    param([string]$InstallDir)

    $CurrentPath = [Environment]::GetEnvironmentVariable("PATH", "User")

    if ($CurrentPath -notlike "*$InstallDir*") {
        $NewPath = "$CurrentPath;$InstallDir"
        [Environment]::SetEnvironmentVariable("PATH", $NewPath, "User")
        Write-Info "Updated PATH with $InstallDir"
    }
}

# Function: Verify installation
function Test-Installation {
    $ExePath = Join-Path $env:USERPROFILE ".local\bin\typedialog.exe"

    if (Test-Path $ExePath) {
        Write-Success "TypeDialog installed successfully"
        return $true
    }
    else {
        Write-Err "Installation verification failed"
        return $false
    }
}

# Main entry point
function Main {
    Write-Host "TypeDialog Installation" -ForegroundColor Yellow
    Write-Host "=======================" -ForegroundColor Yellow

    $Platform = Get-Platform
    Write-Info "Detected platform: $Platform"

    New-DirectoryStructure -InstallDir $InstallDir -ConfigDir $ConfigDir

    $Archive = Get-Release -Platform $Platform -Version $Version
    $ExtractDir = Expand-Release -Archive $Archive

    Install-Binaries -ExtractDir $ExtractDir -InstallDir $InstallDir
    Install-Configs -ExtractDir $ExtractDir -ConfigDir $ConfigDir

    Update-Path -InstallDir $InstallDir

    if (Test-Installation) {
        Write-Success "Installation complete!"
        Write-Info "Install directory: $InstallDir"
        Write-Info "Config directory: $ConfigDir"
    }
    else {
        exit 1
    }
}

Main
