# =================================================================
# LLMHosts - Customer Install Script (Windows PowerShell)
# =================================================================
# One command to go from nothing to running AI infrastructure:
#
#   irm https://llmhosts.com/install.ps1 | iex
#
# What this does:
#   1. Kills any running llmhosts process (Windows file locking)
#   2. Installs uv (Python package manager) if not present
#   3. Installs llmhosts via uv (isolated, on PATH, no venv confusion)
#   4. Runs 'llmhosts up' (detects GPU, installs Ollama, pulls model,
#      starts proxy, authenticates, registers device)
#
# Options (environment variables):
#   $env:LLMHOSTS_VERSION  - Pin a specific version (default: latest)
#   $env:LLMHOSTS_NO_RUN   - Set to 1 to install only
#   $env:LLMHOSTS_FROM_GIT - Set to 1 to install from GitHub main
#   $env:LLMHOSTS_BRANCH   - Git branch to install from (default: main)
# =================================================================

$ErrorActionPreference = 'Stop'

function Write-Step { param([string]$Message) Write-Host "[llmhosts] $Message" -ForegroundColor Green }
function Write-Warn { param([string]$Message) Write-Host "[llmhosts] $Message" -ForegroundColor Yellow }
function Write-Err  { param([string]$Message) Write-Host "[llmhosts] $Message" -ForegroundColor Red }

Write-Host ''
Write-Host '  LLMHosts' -ForegroundColor Cyan -NoNewline
Write-Host ' - Your hardware. Real AI infrastructure. From anywhere.'
Write-Host ''

# --- Step 0: Kill any running llmhosts processes (Windows locks .exe files) ---
$running = Get-Process -Name 'llmhosts' -ErrorAction SilentlyContinue
if (-not $running) {
    # Also check by path — process name might differ
    $running = Get-Process | Where-Object {
        $_.Path -and $_.Path -like '*llmhosts*'
    } -ErrorAction SilentlyContinue
}
if ($running) {
    Write-Warn 'Stopping running llmhosts process...'
    $running | Stop-Process -Force -ErrorAction SilentlyContinue
    Start-Sleep -Seconds 2  # Wait for file handles to release
    Write-Step 'Previous llmhosts process stopped'
}

# --- Step 1: Check Python 3.10+ ---
$pythonCmd = $null
foreach ($cmd in @('python', 'python3', 'py')) {
    try {
        $ver = & $cmd -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')" 2>$null
        if ($ver) {
            $parts = $ver.Split('.')
            if ([int]$parts[0] -ge 3 -and [int]$parts[1] -ge 10) {
                $pythonCmd = $cmd
                break
            }
        }
    } catch { }
}

if (-not $pythonCmd) {
    # Try uv to install Python before giving up
    $uvCheck = Get-Command uv -ErrorAction SilentlyContinue
    if ($uvCheck) {
        Write-Step 'No Python found. Installing Python 3.12 via uv...'
        & uv python install 3.12
        $pythonCmd = 'python'
    } else {
        Write-Err 'Python 3.10+ is required but not found.'
        Write-Host ''
        Write-Host '  Option 1 (recommended): Install uv first, it handles everything:'
        Write-Host '    powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"'
        Write-Host '    Then re-run this script.'
        Write-Host ''
        Write-Host '  Option 2: Install Python directly:'
        Write-Host '    winget install Python.Python.3.12'
        Write-Host '    Or download from https://www.python.org/downloads/'
        Write-Host ''
        exit 1
    }
}

$pyVersion = & $pythonCmd --version 2>&1
Write-Step "Python: $pyVersion"

# --- Step 2: Install uv if not present ---
$uvFound = Get-Command uv -ErrorAction SilentlyContinue
if ($uvFound) {
    $uvVersion = & uv --version 2>&1
    Write-Step "uv: $uvVersion"
} else {
    Write-Step 'Installing uv (fast Python package manager)...'
    powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

    # Refresh PATH for this session — check all known uv install locations
    $pathsToAdd = @(
        (Join-Path $env:USERPROFILE '.local\bin'),
        (Join-Path $env:USERPROFILE '.cargo\bin'),
        (Join-Path $env:USERPROFILE '.uv\bin'),
        (Join-Path $env:APPDATA 'uv\bin')
    )
    foreach ($p in $pathsToAdd) {
        if (Test-Path $p) { $env:PATH = "$p;$env:PATH" }
    }

    $uvCheck = Get-Command uv -ErrorAction SilentlyContinue
    if (-not $uvCheck) {
        Write-Err 'uv installed but not found on PATH. Restart your terminal and re-run.'
        exit 1
    }
    $uvVersion = & uv --version 2>&1
    Write-Step "uv: $uvVersion (just installed)"
}

# --- Step 3: Install llmhosts ---
$fromGit = $env:LLMHOSTS_FROM_GIT -eq '1'
$version = $env:LLMHOSTS_VERSION
$branch = $env:LLMHOSTS_BRANCH

if ($fromGit -or $branch) {
    $ref = if ($branch) { $branch } else { 'main' }
    Write-Step "Installing llmhosts from GitHub ($ref)..."
    & uv tool install --force "llmhosts @ git+https://github.com/LookNoHandsMom/LLMHosts.com.git@$ref"
} elseif ($version) {
    Write-Step "Installing llmhosts==$version..."
    & uv tool install --force "llmhosts==$version"
} else {
    Write-Step 'Installing llmhosts (latest from PyPI)...'
    & uv tool install --force llmhosts
}

if ($LASTEXITCODE -ne 0) {
    Write-Err 'Failed to install llmhosts.'
    exit 1
}

# Ensure uv tool bin is on PATH for this session
$toolBinPaths = @(
    (Join-Path $env:USERPROFILE '.local\bin'),
    (Join-Path $env:APPDATA 'uv\tools-bin')
)
foreach ($p in $toolBinPaths) {
    if ((Test-Path $p) -and ($env:PATH -notlike "*$p*")) {
        $env:PATH = "$p;$env:PATH"
    }
}

$llmCheck = Get-Command llmhosts -ErrorAction SilentlyContinue
if (-not $llmCheck) {
    Write-Err 'llmhosts installed but not found on PATH.'
    Write-Host '  Restart your terminal and run: llmhosts up'
    exit 1
}

try {
    $installedVersion = & llmhosts --version 2>&1
    Write-Step "llmhosts: $installedVersion"
} catch {
    Write-Step 'llmhosts: installed'
}

# --- Step 4: Run llmhosts up ---
$noRun = $env:LLMHOSTS_NO_RUN -eq '1'

if ($noRun) {
    Write-Host ''
    Write-Step 'Installed successfully. Run when ready:'
    Write-Host '  llmhosts up'
    Write-Host ''
} else {
    Write-Host ''
    Write-Step 'Starting LLMHosts...'
    Write-Host ''
    & llmhosts up
}
