#Requires -Version 5.1
<#
.SYNOPSIS
    Deploys ELIDA AI proxy configuration to Windows workstations.

.DESCRIPTION
    This script configures AI coding tools (Claude Code, Continue.dev, Cursor, etc.)
    to route traffic through the ELIDA security proxy.

    Deploy via:
    - Microsoft Intune (Devices → Scripts)
    - SCCM/MECM (Package/Application)
    - Group Policy (Startup/Logon Script)
    - Manual execution

.PARAMETER ElidaHost
    The ELIDA proxy URL. Default: http://elida.corp.local:8080

.PARAMETER SystemWide
    Set environment variables system-wide (requires admin). Default: $true

.EXAMPLE
    .\Deploy-ElidaConfig.ps1
    Deploys with default settings.

.EXAMPLE
    .\Deploy-ElidaConfig.ps1 -ElidaHost "http://proxy.company.com:8080"
    Deploys with custom ELIDA host.

.EXAMPLE
    .\Deploy-ElidaConfig.ps1 -SystemWide $false
    Deploys for current user only (no admin required).

.NOTES
    Author: ELIDA Project
    Version: 1.0.0
#>

param(
    [string]$ElidaHost = "http://elida.corp.local:8080",
    [bool]$SystemWide = $true
)

$ErrorActionPreference = "Stop"

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "  ELIDA Client Configuration Deployment" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "ELIDA Host: $ElidaHost"
Write-Host "System-wide: $SystemWide"
Write-Host ""

# -----------------------------------------------------------------------------
# Environment Variables
# -----------------------------------------------------------------------------
Write-Host "Configuring environment variables..." -ForegroundColor Yellow

$envVars = @{
    "ANTHROPIC_BASE_URL" = $ElidaHost
    "OPENAI_BASE_URL"    = "$ElidaHost/v1"
    "OPENAI_API_BASE"    = "$ElidaHost/v1"
    "MISTRAL_API_BASE"   = $ElidaHost
    "LLM_PROXY_URL"      = $ElidaHost
}

$scope = if ($SystemWide) { "Machine" } else { "User" }

foreach ($var in $envVars.GetEnumerator()) {
    try {
        [Environment]::SetEnvironmentVariable($var.Key, $var.Value, $scope)
        Write-Host "  Set $($var.Key) = $($var.Value)" -ForegroundColor Green
    }
    catch {
        Write-Warning "  Failed to set $($var.Key): $_"
    }
}

# Also set for current process
foreach ($var in $envVars.GetEnumerator()) {
    [Environment]::SetEnvironmentVariable($var.Key, $var.Value, "Process")
}

# -----------------------------------------------------------------------------
# Claude Code CLI
# -----------------------------------------------------------------------------
Write-Host ""
Write-Host "Configuring Claude Code CLI..." -ForegroundColor Yellow

$ClaudeDir = Join-Path $env:USERPROFILE ".claude"
New-Item -ItemType Directory -Force -Path $ClaudeDir | Out-Null

$ClaudeSettings = @{
    env = @{
        ANTHROPIC_BASE_URL = $ElidaHost
    }
} | ConvertTo-Json -Depth 10

$ClaudeSettingsPath = Join-Path $ClaudeDir "settings.json"
$ClaudeSettings | Out-File -FilePath $ClaudeSettingsPath -Encoding UTF8 -Force
Write-Host "  Created: $ClaudeSettingsPath" -ForegroundColor Green

# -----------------------------------------------------------------------------
# Continue.dev (VS Code Extension)
# -----------------------------------------------------------------------------
Write-Host ""
Write-Host "Configuring Continue.dev..." -ForegroundColor Yellow

$ContinueDir = Join-Path $env:USERPROFILE ".continue"
New-Item -ItemType Directory -Force -Path $ContinueDir | Out-Null

$ContinueConfig = @"
# ELIDA-managed Continue.dev configuration
# Generated by Deploy-ElidaConfig.ps1

models:
  # Anthropic Claude
  - name: "claude-3-opus"
    provider: "anthropic"
    apiBase: "$ElidaHost"
    apiKey: "`${ANTHROPIC_API_KEY}"

  - name: "claude-3-sonnet"
    provider: "anthropic"
    apiBase: "$ElidaHost"
    apiKey: "`${ANTHROPIC_API_KEY}"

  # OpenAI GPT
  - name: "gpt-4"
    provider: "openai"
    apiBase: "$ElidaHost/v1"
    apiKey: "`${OPENAI_API_KEY}"

  - name: "gpt-4-turbo"
    provider: "openai"
    apiBase: "$ElidaHost/v1"
    apiKey: "`${OPENAI_API_KEY}"

  # Mistral
  - name: "codestral"
    provider: "mistral"
    apiBase: "$ElidaHost/v1"
    apiKey: "`${MISTRAL_API_KEY}"

# Tab autocomplete model
tabAutocompleteModel:
  provider: "openai"
  apiBase: "$ElidaHost/v1"
  apiKey: "`${OPENAI_API_KEY}"
  model: "gpt-4"
"@

$ContinueConfigPath = Join-Path $ContinueDir "config.yaml"
$ContinueConfig | Out-File -FilePath $ContinueConfigPath -Encoding UTF8 -Force
Write-Host "  Created: $ContinueConfigPath" -ForegroundColor Green

# -----------------------------------------------------------------------------
# Cursor IDE (if installed)
# -----------------------------------------------------------------------------
Write-Host ""
Write-Host "Checking for Cursor IDE..." -ForegroundColor Yellow

$CursorConfigDir = Join-Path $env:APPDATA "Cursor\User"
if (Test-Path $CursorConfigDir) {
    $CursorSettingsPath = Join-Path $CursorConfigDir "settings.json"

    if (Test-Path $CursorSettingsPath) {
        try {
            $cursorSettings = Get-Content $CursorSettingsPath -Raw | ConvertFrom-Json
        }
        catch {
            $cursorSettings = @{}
        }
    }
    else {
        $cursorSettings = @{}
    }

    # Add ELIDA proxy setting
    $cursorSettings | Add-Member -NotePropertyName "cursor.aiBaseUrl" -NotePropertyValue "$ElidaHost/v1" -Force

    $cursorSettings | ConvertTo-Json -Depth 10 | Out-File -FilePath $CursorSettingsPath -Encoding UTF8 -Force
    Write-Host "  Updated: $CursorSettingsPath" -ForegroundColor Green
}
else {
    Write-Host "  Cursor not found (skipping)" -ForegroundColor Gray
}

# -----------------------------------------------------------------------------
# VS Code Settings (global)
# -----------------------------------------------------------------------------
Write-Host ""
Write-Host "Checking for VS Code..." -ForegroundColor Yellow

$VSCodeConfigDir = Join-Path $env:APPDATA "Code\User"
if (Test-Path $VSCodeConfigDir) {
    $VSCodeSettingsPath = Join-Path $VSCodeConfigDir "settings.json"

    if (Test-Path $VSCodeSettingsPath) {
        try {
            $vscodeSettings = Get-Content $VSCodeSettingsPath -Raw | ConvertFrom-Json
        }
        catch {
            $vscodeSettings = @{}
        }
    }
    else {
        $vscodeSettings = @{}
    }

    # Add HTTP proxy settings for extensions that use it
    $vscodeSettings | Add-Member -NotePropertyName "http.proxy" -NotePropertyValue "" -Force
    $vscodeSettings | Add-Member -NotePropertyName "http.proxySupport" -NotePropertyValue "on" -Force

    $vscodeSettings | ConvertTo-Json -Depth 10 | Out-File -FilePath $VSCodeSettingsPath -Encoding UTF8 -Force
    Write-Host "  Updated: $VSCodeSettingsPath" -ForegroundColor Green
}
else {
    Write-Host "  VS Code not found (skipping)" -ForegroundColor Gray
}

# -----------------------------------------------------------------------------
# Summary
# -----------------------------------------------------------------------------
Write-Host ""
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "  Deployment Complete!" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "Configured:" -ForegroundColor White
Write-Host "  - Environment variables ($scope scope)"
Write-Host "  - Claude Code CLI (~\.claude\settings.json)"
Write-Host "  - Continue.dev (~\.continue\config.yaml)"
if (Test-Path (Join-Path $env:APPDATA "Cursor")) {
    Write-Host "  - Cursor IDE"
}
Write-Host ""
Write-Host "To apply changes:" -ForegroundColor Yellow
Write-Host "  1. Sign out and sign back in (for environment variables)"
Write-Host "  2. Restart any running AI coding tools"
Write-Host ""
Write-Host "Verify configuration:" -ForegroundColor Yellow
Write-Host "  Invoke-WebRequest -Uri '$ElidaHost/health'"
