# Vigthoria CLI Installer for Windows
# Usage: irm https://cli.vigthoria.io/install.ps1 | iex
# Alternative: PowerShell -ExecutionPolicy Bypass -File install.ps1

$ErrorActionPreference = "Stop"

# Configuration
$CLI_VERSION = "1.11.24"
$INSTALL_DIR = "$env:USERPROFILE\.vigthoria"
$NPM_PACKAGE = "vigthoria-cli"
$GIT_PACKAGE_URL = "git+https://market.vigthoria.io/vigthoria/vigthoria-cli.git"
$MANIFEST_URL = "https://extension.vigthoria.io/downloads/manifest.json"
$HOSTED_TARBALL_URL = "https://extension.vigthoria.io/downloads/vigthoria-cli-$CLI_VERSION.tgz"

function Resolve-ReleaseManifest {
    try {
        $manifest = Invoke-WebRequest -Uri $MANIFEST_URL -UseBasicParsing -TimeoutSec 10 -ErrorAction Stop |
            Select-Object -ExpandProperty Content |
            ConvertFrom-Json
        $stable = $manifest.channels.stable
        if ($stable.version) {
            $script:CLI_VERSION = [string]$stable.version
        }
        if ($stable.url) {
            $script:HOSTED_TARBALL_URL = [string]$stable.url
        } elseif ($stable.version) {
            $script:HOSTED_TARBALL_URL = "https://extension.vigthoria.io/downloads/vigthoria-cli-$($stable.version).tgz"
        }
    } catch {
        Write-Host "Release manifest unavailable, using bundled fallback $CLI_VERSION" -ForegroundColor Yellow
    }
}

Resolve-ReleaseManifest

function Write-Banner {
    Write-Host ""
    Write-Host "  ╔═══════════════════════════════════════════════════════════╗" -ForegroundColor Cyan
    Write-Host "  ║                                                           ║" -ForegroundColor Cyan
    Write-Host "  ║         VIGTHORIA CLI INSTALLER v$CLI_VERSION                  ║" -ForegroundColor Cyan
    Write-Host "  ║         AI-Powered Terminal Coding Assistant              ║" -ForegroundColor Cyan
    Write-Host "  ║                                                           ║" -ForegroundColor Cyan
    Write-Host "  ╚═══════════════════════════════════════════════════════════╝" -ForegroundColor Cyan
    Write-Host ""
}

function Test-NetworkConnectivity {
    Write-Host "🔍 Checking network connectivity..." -ForegroundColor Yellow

    try {
        $response = Invoke-WebRequest -Uri $HOSTED_TARBALL_URL -Method Head -UseBasicParsing -TimeoutSec 10 -ErrorAction Stop
        Write-Host "✓ hosted CLI package is reachable" -ForegroundColor Green
        return $true
    }
    catch {
        Write-Host "⚠ Hosted package unavailable, checking npm registry..." -ForegroundColor Yellow
    }

    try {
        $response = Invoke-WebRequest -Uri "https://registry.npmjs.org/vigthoria-cli" -UseBasicParsing -TimeoutSec 10 -ErrorAction Stop
        Write-Host "✓ npm registry is reachable" -ForegroundColor Green
        return $true
    }
    catch {
        Write-Host "✗ Cannot reach hosted package or npm registry" -ForegroundColor Red
        return $false
    }
}

function Test-Prerequisites {
    Write-Host "🔍 Checking prerequisites..." -ForegroundColor Yellow
    
    # Check Node.js
    try {
        $nodeVersion = node -v 2>$null
        if ($nodeVersion) {
            $major = [int]($nodeVersion -replace 'v(\d+)\..*', '$1')
            if ($major -ge 18) {
                Write-Host "✓ Node.js $nodeVersion" -ForegroundColor Green
            } else {
                Write-Host "✗ Node.js 18+ required (found $nodeVersion)" -ForegroundColor Red
                Write-Host "  Download from: https://nodejs.org/" -ForegroundColor Yellow
                return $false
            }
        }
    }
    catch {
        Write-Host "✗ Node.js is not installed" -ForegroundColor Red
        Write-Host ""
        Write-Host "Please install Node.js first:" -ForegroundColor Yellow
        Write-Host "  Option 1: winget install OpenJS.NodeJS" -ForegroundColor White
        Write-Host "  Option 2: Download from https://nodejs.org/" -ForegroundColor White
        Write-Host ""
        return $false
    }
    
    # Check npm
    try {
        $npmVersion = npm -v 2>$null
        if ($npmVersion) {
            Write-Host "✓ npm v$npmVersion" -ForegroundColor Green
        }
    }
    catch {
        Write-Host "✗ npm is not installed" -ForegroundColor Red
        return $false
    }
    
    return $true
}

function Install-VigthoriaCLI-NPM {
    Write-Host ""
    Write-Host "📦 Installing Vigthoria CLI..." -ForegroundColor Cyan

    try {
        npm install -g $HOSTED_TARBALL_URL
        Write-Host "✓ Vigthoria CLI installed successfully!" -ForegroundColor Green
        return $true
    }
    catch {
        Write-Host "⚠ Hosted package install failed, trying npm registry..." -ForegroundColor Yellow
    }

    try {
        npm install -g vigthoria-cli
        Write-Host "✓ Vigthoria CLI installed successfully!" -ForegroundColor Green
        return $true
    }
    catch {
        Write-Host "⚠ npm registry install failed, trying git package..." -ForegroundColor Yellow
    }

    try {
        npm install -g $GIT_PACKAGE_URL
        Write-Host "✓ Vigthoria CLI installed successfully from git package!" -ForegroundColor Green
        return $true
    }
    catch {
        Write-Host "✗ install failed (hosted package + npm registry + git package): $_" -ForegroundColor Red
        return $false
    }
}

function Install-VigthoriaCLI-Direct {
    Write-Host ""
    Write-Host "📦 Installing Vigthoria CLI (Direct Download)..." -ForegroundColor Cyan
    
    # Create install directory
    if (-not (Test-Path $INSTALL_DIR)) {
        New-Item -ItemType Directory -Path $INSTALL_DIR -Force | Out-Null
    }
    
    $tarballUrl = $HOSTED_TARBALL_URL
    $tarballPath = "$INSTALL_DIR\vigthoria-cli.tgz"
    $extractPath = "$INSTALL_DIR\cli"
    
    try {
        # Download tarball
        Write-Host "  Downloading from $tarballUrl..." -ForegroundColor Gray
        Invoke-WebRequest -Uri $tarballUrl -OutFile $tarballPath -UseBasicParsing
        
        # Extract
        Write-Host "  Extracting..." -ForegroundColor Gray
        if (Test-Path $extractPath) {
            Remove-Item -Recurse -Force $extractPath
        }
        New-Item -ItemType Directory -Path $extractPath -Force | Out-Null
        
        # Use tar to extract (available in Windows 10+)
        tar -xzf $tarballPath -C $extractPath
        
        # The tarball extracts to a 'package' folder
        $packagePath = "$extractPath\package"
        
        # Install dependencies
        Write-Host "  Installing dependencies..." -ForegroundColor Gray
        Push-Location $packagePath
        npm install --production
        Pop-Location
        
        # Create batch file wrapper
        $batContent = @"
@echo off
node "$packagePath\dist\index.js" %*
"@
        Set-Content -Path "$INSTALL_DIR\vigthoria.bat" -Value $batContent
        Set-Content -Path "$INSTALL_DIR\vig.bat" -Value $batContent
        
        # Add to PATH if not already there
        $userPath = [Environment]::GetEnvironmentVariable("PATH", "User")
        if ($userPath -notlike "*$INSTALL_DIR*") {
            [Environment]::SetEnvironmentVariable("PATH", "$userPath;$INSTALL_DIR", "User")
            Write-Host "  Added $INSTALL_DIR to PATH" -ForegroundColor Gray
        }
        
        # Cleanup
        Remove-Item $tarballPath -Force
        
        Write-Host "✓ Vigthoria CLI installed successfully!" -ForegroundColor Green
        return $true
    }
    catch {
        Write-Host "✗ Direct install failed: $_" -ForegroundColor Red
        return $false
    }
}

function Install-VigthoriaCLI-GitHub {
    Write-Host ""
    Write-Host "📦 Installing Vigthoria CLI (from Vigthoria Market)..." -ForegroundColor Cyan
    
    # Create install directory
    if (-not (Test-Path $INSTALL_DIR)) {
        New-Item -ItemType Directory -Path $INSTALL_DIR -Force | Out-Null
    }
    
    $clonePath = "$INSTALL_DIR\cli"
    
    try {
        # Check if git is available
        $gitVersion = git --version 2>$null
        if (-not $gitVersion) {
            Write-Host "✗ Git is not installed" -ForegroundColor Red
            return $false
        }
        
        # Clone repository
        if (Test-Path $clonePath) {
            Remove-Item -Recurse -Force $clonePath
        }
        
        Write-Host "  Cloning from Vigthoria Market..." -ForegroundColor Gray
        git clone --depth 1 https://market.vigthoria.io/vigthoria/vigthoria-cli.git $clonePath
        
        # Install and build
        Push-Location $clonePath
        Write-Host "  Installing dependencies..." -ForegroundColor Gray
        npm install
        Write-Host "  Building..." -ForegroundColor Gray
        npm run build
        Write-Host "  Linking globally..." -ForegroundColor Gray
        npm link
        Pop-Location
        
        Write-Host "✓ Vigthoria CLI installed successfully!" -ForegroundColor Green
        return $true
    }
    catch {
        Write-Host "✗ GitHub install failed: $_" -ForegroundColor Red
        return $false
    }
}

function Show-NetworkTroubleshooting {
    Write-Host ""
    Write-Host "═══════════════════════════════════════════════════════════════" -ForegroundColor Yellow
    Write-Host "  NETWORK TROUBLESHOOTING" -ForegroundColor Yellow
    Write-Host "═══════════════════════════════════════════════════════════════" -ForegroundColor Yellow
    Write-Host ""
    Write-Host "The hosted package and npm registry could not be reached. Try these solutions:" -ForegroundColor White
    Write-Host ""
    Write-Host "1. Check your internet connection" -ForegroundColor Cyan
    Write-Host "   ping registry.npmjs.org" -ForegroundColor Gray
    Write-Host ""
    Write-Host "2. If behind a corporate proxy, configure npm:" -ForegroundColor Cyan
    Write-Host "   npm config set proxy http://proxy.company.com:8080" -ForegroundColor Gray
    Write-Host "   npm config set https-proxy http://proxy.company.com:8080" -ForegroundColor Gray
    Write-Host ""
    Write-Host "3. Try a different npm registry:" -ForegroundColor Cyan
    Write-Host "   npm config set registry https://registry.npmmirror.com" -ForegroundColor Gray
    Write-Host ""
    Write-Host "4. Check Windows Firewall/Antivirus settings" -ForegroundColor Cyan
    Write-Host ""
    Write-Host "5. Try using a VPN" -ForegroundColor Cyan
    Write-Host ""
    Write-Host "6. Manual download alternatives:" -ForegroundColor Cyan
    Write-Host "   Hosted package: $HOSTED_TARBALL_URL" -ForegroundColor Gray
    Write-Host "   npm package: https://www.npmjs.com/package/vigthoria-cli" -ForegroundColor Gray
    Write-Host "   git package: $GIT_PACKAGE_URL" -ForegroundColor Gray
    Write-Host ""
}

function Show-Success {
    Write-Host ""
    Write-Host "═══════════════════════════════════════════════════════════════" -ForegroundColor Green
    Write-Host "  INSTALLATION COMPLETE!" -ForegroundColor Green
    Write-Host "═══════════════════════════════════════════════════════════════" -ForegroundColor Green
    Write-Host ""
    Write-Host "  Get started:" -ForegroundColor White
    Write-Host "    1. Open a new terminal" -ForegroundColor Gray
    Write-Host "    2. Login: vigthoria login" -ForegroundColor Gray
    Write-Host "    3. Start: vigthoria chat" -ForegroundColor Gray
    Write-Host "       Or local project start: npx vigthoria-chat" -ForegroundColor Gray
    Write-Host ""
    Write-Host "  Commands:" -ForegroundColor White
    Write-Host "    vigthoria chat   - Start AI chat" -ForegroundColor Gray
    Write-Host "    vigthoria-chat   - Start chat directly" -ForegroundColor Gray
    Write-Host "    vigthoria edit   - Edit files with AI" -ForegroundColor Gray
    Write-Host "    vigthoria repo   - Manage cloud repos" -ForegroundColor Gray
    Write-Host "    vig --help       - Show all commands" -ForegroundColor Gray
    Write-Host ""
    Write-Host "  Documentation: https://docs.vigthoria.io/cli" -ForegroundColor Cyan
    Write-Host ""
}

# Main installation flow
Write-Banner

if (-not (Test-Prerequisites)) {
    exit 1
}

$networkOk = Test-NetworkConnectivity

if ($networkOk) {
    # Try npm install first
    if (Install-VigthoriaCLI-NPM) {
        Show-Success
        exit 0
    }
}

# Network failed or npm install failed
Show-NetworkTroubleshooting

Write-Host "Would you like to try alternative installation methods?" -ForegroundColor Yellow
$choice = Read-Host "Enter 'y' to try direct download, 'g' for git clone, or 'n' to exit"

switch ($choice.ToLower()) {
    'y' {
        if (Install-VigthoriaCLI-Direct) {
            Show-Success
        }
    }
    'g' {
        if (Install-VigthoriaCLI-GitHub) {
            Show-Success
        }
    }
    default {
        Write-Host "Installation cancelled." -ForegroundColor Gray
    }
}
