#
# AI Code Toolkits - Installer (Windows PowerShell)
# Cài đặt offline, chỉ cần Node.js >= 18
#
# Usage: .\install.ps1
#

$ErrorActionPreference = "Stop"

$InstallDir = Join-Path $env:USERPROFILE ".ai-code-toolkits"

Write-Host ""
Write-Host "⚡ AI Code Toolkits — Installer" -ForegroundColor Cyan
Write-Host ""

# Check node
$nodeExists = Get-Command node -ErrorAction SilentlyContinue
if (-not $nodeExists) {
    Write-Host "[ERROR] Node.js không tìm thấy" -ForegroundColor Red
    Write-Host "Cài đặt: https://nodejs.org/en/download/"
    exit 1
}

$nodeVersion = (node --version) -replace 'v','' -split '\.' | Select-Object -First 1
if ([int]$nodeVersion -lt 18) {
    Write-Host "[ERROR] Cần Node.js >= 18 (hiện tại: $(node --version))" -ForegroundColor Red
    exit 1
}

# Create install dir
Write-Host "-> Cài đặt vào $InstallDir..."
if (-not (Test-Path $InstallDir)) {
    New-Item -Path $InstallDir -ItemType Directory -Force | Out-Null
}

# Copy all files
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$Files = @("server.js", "patcher.js", "ag-injector.js", "auto-script.js", "index.html", "package.json", "install.ps1", "install.sh", "INSTALL_GUIDE.md")

foreach ($file in $Files) {
    $src = Join-Path $ScriptDir $file
    if (Test-Path $src) {
        Copy-Item $src $InstallDir -Force
    } else {
        Write-Host "[WARNING] Không tìm thấy $file" -ForegroundColor Yellow
    }
}
Write-Host "   Done" -ForegroundColor Green
Write-Host ""

# Start server
Write-Host "-> Khởi động server..."
Write-Host ""
Write-Host "================================================" -ForegroundColor Cyan
Write-Host "  Mở browser: http://localhost:3456" -ForegroundColor White
Write-Host "  Nhấn Ctrl+C để dừng" -ForegroundColor Gray
Write-Host "================================================" -ForegroundColor Cyan
Write-Host ""

Set-Location $InstallDir
node server.js
