#!/usr/bin/env pwsh
################################################################################
# SuperCharge Claude Code - Windows PowerShell Installer
################################################################################
# This script transforms any Claude Code installation into a supercharged
# version with all customizations, skills, agents, plugins, and integrations.
#
# Usage:
#   pwsh -ExecutionPolicy Bypass -File install-windows.ps1
#   OR right-click -> "Run with PowerShell"
#
# Features:
# - 30+ Custom Skills (cognitive, development, UI/UX)
# - RalphLoop autonomous agent integration
# - Multi-AI consultation (Qwen integration)
# - Agent management system
# - Custom hooks and commands
# - MCP servers integration
################################################################################

#Requires -Version 5.1

[CmdletBinding()]
param()

# Colors for output
function Write-ColorOutput {
    param(
        [Parameter(Mandatory=$true)]
        [string]$Message,

        [Parameter(Mandatory=$false)]
        [ValidateSet("Info", "Success", "Warning", "Error", "Step")]
        [string]$Type = "Info"
    )

    $colors = @{
        "Info" = "Cyan"
        "Success" = "Green"
        "Warning" = "Yellow"
        "Error" = "Red"
        "Step" = "Magenta"
    }

    $prefixes = @{
        "Info" = "[INFO]"
        "Success" = "[SUCCESS]"
        "Warning" = "[WARN]"
        "Error" = "[ERROR]"
        "Step" = "==>"
    }

    Write-Host "$($prefixes[$Type]) $Message" -ForegroundColor $colors[$Type]
}

function Show-Banner {
    Write-Host @"

╔═══════════════════════════════════════════════════════════════╗
║                                                               ║
║   ███████╗██╗      █████╗  ██████╗                          ║
║   ██╔════╝██║     ██╔══██╗██╔════╝                          ║
║   ███████╗██║     ███████║██║  ███╗                         ║
║   ╚════██║██║     ██╔══██║██║   ██║                         ║
║   ███████║███████╗██║  ██║╚██████╔╝                         ║
║   ╚══════╝╚══════╝╚═╝  ╚═╝ ╚═════╝                          ║
║                                                               ║
║          ███████╗██╗  ██╗███████╗███╗   ██╗                  ║
║          ██╔════╝╚██╗██╔╝██╔════╝████╗  ██║                  ║
║          █████╗   ╚███╔╝ █████╗  ██╔██╗ ██║                  ║
║          ██╔══╝   ██╔██╗ ██╔══╝  ██║╚██╗██║                  ║
║          ███████╗██║██╗██║███████╗██║ ╚████║                  ║
║          ╚══════╝╚═╝╚═╝╚═╝╚══════╝╚═╝  ╚═══╝                  ║
║                                                               ║
║              Windows PowerShell Installer                     ║
║                                                               ║
╚═══════════════════════════════════════════════════════════════╝

"@ -ForegroundColor Cyan

    # Show warning about experimental status
    Write-Host ""
    Write-Host "⚠️  WARNING: This PowerShell installer is EXPERIMENTAL and may have bugs." -ForegroundColor Yellow
    Write-Host "   For reliable installation, we recommend using WSL instead:" -ForegroundColor Yellow
    Write-Host "   wsl bash -c 'git clone https://github.rommark.dev/admin/SuperCharged-Claude-Code-Upgrade.git && cd SuperCharged-Claude-Code-Upgrade && ./supercharge.sh'" -ForegroundColor White
    Write-Host ""
    Write-Host "   Press Ctrl+C to exit and use WSL, or press Enter to continue..." -ForegroundColor Cyan
    Read-Host
    Write-Host ""
}

function Test-ClaudeCode {
    Write-ColorOutput "Checking for Claude Code installation..." -Type Step

    $claudeCmd = Get-Command claude -ErrorAction SilentlyContinue

    if (-not $claudeCmd) {
        Write-ColorOutput "Claude Code CLI not found!" -Type Warning
        Write-Host ""
        Write-Host "Claude Code is required to use these customizations." -ForegroundColor Yellow
        Write-Host ""
        Write-Host "Installation options:" -ForegroundColor White
        Write-Host "  1. Install Claude Code with npm (requires Node.js)"
        Write-Host "  2. Install manually later"
        Write-Host "  3. Exit to install first"
        Write-Host ""

        $choice = Read-Host "Choose option [1/2/3]"
        Write-Host ""

        switch ($choice) {
            "1" {
                Write-ColorOutput "Installing Claude Code via npm..." -Type Info
                try {
                    npm install -g @anthropic-ai/claude-code
                    if ($LASTEXITCODE -eq 0) {
                        Write-ColorOutput "Claude Code installed successfully!" -Type Success
                    } else {
                        Write-ColorOutput "Claude Code installation failed. Please install manually." -Type Error
                        exit 1
                    }
                } catch {
                    Write-ColorOutput "npm install failed: $_" -Type Error
                    Write-ColorOutput "Please install Node.js from https://nodejs.org/ and try again." -Type Info
                    exit 1
                }
            }
            "2" {
                Write-ColorOutput "Skipping Claude Code installation." -Type Warning
                Write-ColorOutput "You can install it later with: npm install -g @anthropic-ai/claude-code" -Type Info
                return $false
            }
            "3" {
                Write-ColorOutput "Please install Claude Code first:" -Type Info
                Write-Host "  npm install -g @anthropic-ai/claude-code" -ForegroundColor White
                exit 1
            }
            default {
                Write-ColorOutput "Invalid choice." -Type Error
                exit 1
            }
        }
    }

    # Refresh path and check again
    $claudeCmd = Get-Command claude -ErrorAction SilentlyContinue
    if ($claudeCmd) {
        $version = & claude --version 2>$null
        Write-ColorOutput "Claude Code found: $version" -Type Success
        return $true
    }

    return $false
}

function Backup-ExistingConfig {
    Write-ColorOutput "Backing up existing configuration..." -Type Step

    $claudeDir = Join-Path $env:USERPROFILE ".claude"
    $backupDir = Join-Path $env:USERPROFILE ".claude-backup-$(Get-Date -Format 'yyyyMMdd_HHmmss')"

    if (Test-Path $claudeDir) {
        # Use Robocopy to handle reserved device names (nul, con, prn, etc.)
        $robocopyResult = robocopy $claudeDir $backupDir /E /R:0 /W:0 /NFL /NDL /NJH /NJS 2>&1

        if ($LASTEXITCODE -lt 8) {
            Write-ColorOutput "Backup created at: $backupDir" -Type Success
        } else {
            Write-ColorOutput "Backup had some issues (continued anyway)." -Type Warning
        }
    } else {
        Write-ColorOutput "No existing configuration to backup." -Type Info
    }
}

function Install-Dependencies {
    Write-ColorOutput "Checking dependencies..." -Type Step

    # Check Node.js
    $nodeCmd = Get-Command node -ErrorAction SilentlyContinue
    if ($nodeCmd) {
        $version = & node --version
        Write-ColorOutput "Node.js found: $version" -Type Success
    } else {
        Write-ColorOutput "Node.js not found. Some features may not work." -Type Warning
    }

    # Check Git
    $gitCmd = Get-Command git -ErrorAction SilentlyContinue
    if (-not $gitCmd) {
        Write-ColorOutput "Git not found. Please install Git from https://git-scm.com/" -Type Error
        exit 1
    } else {
        $version = & git --version
        Write-ColorOutput "Git found: $version" -Type Success
    }

    # Check Python (optional)
    $pythonCmd = Get-Command python -ErrorAction SilentlyContinue
    if (-not $pythonCmd) {
        $pythonCmd = Get-Command python3 -ErrorAction SilentlyContinue
    }

    if ($pythonCmd) {
        $version = & $pythonCmd --version
        Write-ColorOutput "Python found: $version" -Type Success

        # Try to install Ralph Orchestrator
        Write-ColorOutput "Installing Ralph Orchestrator..." -Type Info
        try {
            & $pythonCmd -m pip install ralph-orchestrator 2>$null
            if ($LASTEXITCODE -eq 0) {
                Write-ColorOutput "Ralph Orchestrator installed." -Type Success
            }
        } catch {
            Write-ColorOutput "Could not install Ralph Orchestrator (optional)." -Type Warning
        }
    } else {
        Write-ColorOutput "Python not found. Some features may not work." -Type Warning
    }
}

function Download-Repository {
    Write-ColorOutput "Downloading SuperCharge Claude Code package..." -Type Step

    $tempDir = Join-Path $env:TEMP "SuperCharged-Claude-Code-Upgrade"
    $zipFile = Join-Path $env:TEMP "supercharge.zip"
    $repoUrl = "https://github.rommark.dev/admin/SuperCharged-Claude-Code-Upgrade/archive/refs/heads/main.zip"

    # Clean up any existing download
    if (Test-Path $tempDir) {
        Remove-Item -Path $tempDir -Recurse -Force -ErrorAction SilentlyContinue
    }
    if (Test-Path $zipFile) {
        Remove-Item -Path $zipFile -Force -ErrorAction SilentlyContinue
    }

    # Download the repository
    try {
        Write-ColorOutput "Downloading from: $repoUrl" -Type Info
        Invoke-WebRequest -Uri $repoUrl -OutFile $zipFile -UseBasicParsing

        # Extract the zip
        Write-ColorOutput "Extracting files..." -Type Info
        Expand-Archive -Path $zipFile -DestinationPath $env:TEMP -Force

        # Rename the extracted folder
        $extractedDir = Join-Path $env:TEMP "SuperCharged-Claude-Code-Upgrade-main"
        if (Test-Path $extractedDir) {
            Move-Item -Path $extractedDir -Destination $tempDir -Force
        }

        Write-ColorOutput "Repository downloaded to: $tempDir" -Type Success
        return $tempDir
    } catch {
        Write-ColorOutput "Failed to download repository: $_" -Type Error
        return $null
    }
}

function Copy-DirectoryContent {
    param(
        [string]$Source,
        [string]$Destination
    )

    if (Test-Path $Source) {
        # Create destination if it doesn't exist
        if (-not (Test-Path $Destination)) {
            New-Item -Path $Destination -ItemType Directory -Force | Out-Null
        }

        # Copy all contents from source to destination
        # Using -Container to properly handle nested directories
        Copy-Item -Path "$Source\*" -Destination $Destination -Recurse -Force -ErrorAction SilentlyContinue
        return $true
    }
    return $false
}

function Install-Skills {
    param([string]$SourceDir)

    Write-ColorOutput "Installing custom skills..." -Type Step

    $claudeDir = Join-Path $env:USERPROFILE ".claude"
    $skillsDir = Join-Path $SourceDir "skills"
    $destDir = Join-Path $claudeDir "skills"

    if (Copy-DirectoryContent -Source $skillsDir -Destination $destDir) {
        $count = (Get-ChildItem -Path $destDir -Filter "SKILL.md" -Recurse -ErrorAction SilentlyContinue).Count
        Write-ColorOutput "Installed $count custom skills." -Type Success
    } else {
        Write-ColorOutput "Skills directory not found in source." -Type Warning
    }
}

function Install-Agents {
    param([string]$SourceDir)

    Write-ColorOutput "Installing agent management system..." -Type Step

    $claudeDir = Join-Path $env:USERPROFILE ".claude"
    $agentsDir = Join-Path $SourceDir "agents"
    $destDir = Join-Path $claudeDir "agents"

    if (Copy-DirectoryContent -Source $agentsDir -Destination $destDir) {
        Write-ColorOutput "Agent management system installed." -Type Success
    } else {
        Write-ColorOutput "Agents directory not found in source." -Type Warning
    }
}

function Install-Hooks {
    param([string]$SourceDir)

    Write-ColorOutput "Installing custom hooks..." -Type Step

    $claudeDir = Join-Path $env:USERPROFILE ".claude"
    $hooksDir = Join-Path $SourceDir "hooks"
    $destDir = Join-Path $claudeDir "hooks"

    if (Copy-DirectoryContent -Source $hooksDir -Destination $destDir) {
        Write-ColorOutput "Custom hooks installed." -Type Success
    } else {
        Write-ColorOutput "Hooks directory not found in source." -Type Warning
    }
}

function Install-Commands {
    param([string]$SourceDir)

    Write-ColorOutput "Installing custom commands..." -Type Step

    $claudeDir = Join-Path $env:USERPROFILE ".claude"
    $commandsDir = Join-Path $SourceDir "commands"
    $destDir = Join-Path $claudeDir "commands"

    if (Copy-DirectoryContent -Source $commandsDir -Destination $destDir) {
        $count = (Get-ChildItem -Path $destDir -ErrorAction SilentlyContinue).Count
        Write-ColorOutput "Installed $count custom commands." -Type Success
    } else {
        Write-ColorOutput "Commands directory not found in source." -Type Warning
    }
}

function Install-Plugins {
    param([string]$SourceDir)

    Write-ColorOutput "Installing plugin references..." -Type Step

    $claudeDir = Join-Path $env:USERPROFILE ".claude"
    $pluginsDir = Join-Path $SourceDir "plugins"
    $destDir = Join-Path $claudeDir "plugins"

    if (Copy-DirectoryContent -Source $pluginsDir -Destination $destDir) {
        $count = (Get-ChildItem -Path $destDir -Directory -ErrorAction SilentlyContinue).Count
        Write-ColorOutput "Installed $count plugin references." -Type Success
    } else {
        Write-ColorOutput "Plugins directory not found in source." -Type Warning
    }
}

function Install-Scripts {
    param([string]$SourceDir)

    Write-ColorOutput "Installing utility scripts..." -Type Step

    $claudeDir = Join-Path $env:USERPROFILE ".claude"
    $scriptsDir = Join-Path $SourceDir "scripts"
    $destDir = Join-Path $claudeDir "scripts"

    if (Copy-DirectoryContent -Source $scriptsDir -Destination $destDir) {
        Write-ColorOutput "Utility scripts installed." -Type Success
    } else {
        Write-ColorOutput "Scripts directory not found in source." -Type Warning
    }
}

function Install-Templates {
    param([string]$SourceDir)

    Write-ColorOutput "Installing configuration templates..." -Type Step

    $claudeDir = Join-Path $env:USERPROFILE ".claude"
    $templatesDir = Join-Path $SourceDir "templates"

    if (Test-Path $templatesDir) {
        # Install config.json if not exists
        $configJson = Join-Path $templatesDir "config.json"
        if ((Test-Path $configJson) -and -not (Test-Path (Join-Path $claudeDir "config.json"))) {
            Copy-Item -Path $configJson -Destination (Join-Path $claudeDir "config.json") -Force
            Write-ColorOutput "config.json installed." -Type Success
        }

        # Install hooks.json if not exists
        $hooksJson = Join-Path $templatesDir "hooks.json"
        if ((Test-Path $hooksJson) -and -not (Test-Path (Join-Path $claudeDir "hooks.json"))) {
            Copy-Item -Path $hooksJson -Destination (Join-Path $claudeDir "hooks.json") -Force
            Write-ColorOutput "hooks.json installed." -Type Success
        }

        # Install settings.local.json if not exists
        $settingsLocalJson = Join-Path $templatesDir "settings.local.json"
        if ((Test-Path $settingsLocalJson) -and -not (Test-Path (Join-Path $claudeDir "settings.local.json"))) {
            Copy-Item -Path $settingsLocalJson -Destination (Join-Path $claudeDir "settings.local.json") -Force
            Write-ColorOutput "settings.local.json installed." -Type Success
        }
    } else {
        Write-ColorOutput "Templates directory not found." -Type Warning
    }
}

function Show-Summary {
    $claudeDir = Join-Path $env:USERPROFILE ".claude"

    Write-Host ""
    Write-Host "╔═══════════════════════════════════════════════════════════════╗" -ForegroundColor Green
    Write-Host "║                   INSTALLATION COMPLETE!                       ║" -ForegroundColor Green
    Write-Host "╚═══════════════════════════════════════════════════════════════╝" -ForegroundColor Green
    Write-Host ""
    Write-Host "Your Claude Code installation is now SUPERCHARGED!" -ForegroundColor Green
    Write-Host ""
    Write-Host "Installed Features:" -ForegroundColor Cyan
    Write-Host "  [OK] 30+ Custom Skills (cognitive, development, UI/UX)" -ForegroundColor Green
    Write-Host "  [OK] RalphLoop Autonomous Agent Integration" -ForegroundColor Green
    Write-Host "  [OK] Multi-AI Consultation (Qwen)" -ForegroundColor Green
    Write-Host "  [OK] Agent Management System" -ForegroundColor Green
    Write-Host "  [OK] Custom Hooks & Commands" -ForegroundColor Green
    Write-Host "  [OK] Plugin Marketplace Setup" -ForegroundColor Green
    Write-Host ""
    Write-Host "New Commands Available:" -ForegroundColor Cyan
    Write-Host "  /ralph        - Autonomous 'Tackle Until Solved' agent" -ForegroundColor Yellow
    Write-Host "  /brainstorm   - Multi-AI brainstorming session" -ForegroundColor Yellow
    Write-Host "  /write-plan   - Create implementation plans" -ForegroundColor Yellow
    Write-Host "  /execute-plan - Execute written plans" -ForegroundColor Yellow
    Write-Host ""
    Write-Host "Quick Start:" -ForegroundColor Cyan
    Write-Host "  1. Close and reopen your terminal" -ForegroundColor White
    Write-Host "  2. Run Claude Code: claude" -ForegroundColor Yellow
    Write-Host "  3. Try: /ralph 'Design a microservices architecture'" -ForegroundColor Yellow
    Write-Host ""
    Write-Host "Configuration:" -ForegroundColor Cyan
    Write-Host "  Config dir: $claudeDir" -ForegroundColor Yellow
    Write-Host ""
    Write-Host "Enjoy your supercharged Claude Code experience!" -ForegroundColor Green
    Write-Host ""
}

################################################################################
# Main Installation
################################################################################

function Main {
    Show-Banner

    # Check for Claude Code
    $claudeInstalled = Test-ClaudeCode
    if (-not $claudeInstalled) {
        Write-Host ""
        Write-Host "Customizations installed. Install Claude Code to use them." -ForegroundColor Cyan
        Write-Host ""
        Write-Host "Install Claude Code:" -ForegroundColor Cyan
        Write-Host "  npm install -g @anthropic-ai/claude-code" -ForegroundColor White
        Write-Host ""
        return
    }

    # Run installation steps
    Backup-ExistingConfig
    Install-Dependencies

    # Download the repository
    $repoDir = Download-Repository
    if (-not $repoDir) {
        Write-ColorOutput "Failed to download repository. Installation aborted." -Type Error
        exit 1
    }

    # Install all components
    Install-Skills -SourceDir $repoDir
    Install-Agents -SourceDir $repoDir
    Install-Hooks -SourceDir $repoDir
    Install-Commands -SourceDir $repoDir
    Install-Plugins -SourceDir $repoDir
    Install-Scripts -SourceDir $repoDir
    Install-Templates -SourceDir $repoDir

    # Clean up
    Write-ColorOutput "Cleaning up temporary files..." -Type Info
    $zipFile = Join-Path $env:TEMP "supercharge.zip"
    if (Test-Path $zipFile) {
        Remove-Item -Path $zipFile -Force -ErrorAction SilentlyContinue
    }

    Show-Summary
}

# Run main function
try {
    Main
} catch {
    Write-ColorOutput "Installation failed: $_" -Type Error
    exit 1
}
