#Requires -Version 5.1
<#
.SYNOPSIS
    Clean slate for LLMHosts customer experience test.

.DESCRIPTION
    Removes all traces of LLMHosts and Ollama so we can test a true
    first-time customer experience. Run this BEFORE run-alienware.ps1.

    What it removes:
      - llmhosts pip package
      - ~/.llmhosts/ config/data directory
      - Ollama (via winget uninstall)
      - Ollama data (~/.ollama/ models, manifests, blobs)

    What it does NOT touch:
      - Python itself
      - pip itself
      - Other pip packages
      - GPU drivers

.EXAMPLE
    .\clean-alienware.ps1
    .\clean-alienware.ps1 -KeepOllama    # Only remove llmhosts, keep Ollama
#>

param(
    [switch]$KeepOllama
)

Set-StrictMode -Version Latest

function Write-Step($msg) {
    Write-Host "`n--- $msg ---" -ForegroundColor Cyan
}

function Write-Done($msg) {
    Write-Host "  $msg" -ForegroundColor Green
}

function Write-Skip($msg) {
    Write-Host "  $msg" -ForegroundColor DarkGray
}

Write-Host ""
Write-Host "========================================" -ForegroundColor Yellow
Write-Host "  LLMHosts - Clean Slate" -ForegroundColor Yellow
Write-Host "========================================" -ForegroundColor Yellow
Write-Host "  This removes LLMHosts + Ollama so you" -ForegroundColor DarkGray
Write-Host "  can test a true first-time experience." -ForegroundColor DarkGray

# ── 1. Uninstall llmhosts pip package ────────────────────────
Write-Step "Uninstalling llmhosts pip package"

$pipList = pip list --format=json 2>$null | ConvertFrom-Json -ErrorAction SilentlyContinue
$hasLLMHosts = $pipList | Where-Object { $_.name -eq "llmhosts" }

if ($hasLLMHosts) {
    pip uninstall llmhosts -y 2>&1 | Out-Null
    Write-Done "llmhosts uninstalled (was v$($hasLLMHosts.version))"
} else {
    Write-Skip "llmhosts not installed"
}

# ── 2. Remove llmhosts config/data directory ─────────────────
Write-Step "Removing ~/.llmhosts/ data directory"

$llmhostsDir = Join-Path $env:USERPROFILE ".llmhosts"
if (Test-Path $llmhostsDir) {
    $size = (Get-ChildItem $llmhostsDir -Recurse -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum).Sum
    $sizeMB = [math]::Round($size / 1MB, 1)
    Remove-Item $llmhostsDir -Recurse -Force -ErrorAction SilentlyContinue
    Write-Done ("Removed " + $llmhostsDir + " (" + $sizeMB + " MB)")
} else {
    Write-Skip '~/.llmhosts/ does not exist'
}

# ── 3. Remove llmhosts config dir (alternative location) ─────
$llmhostsConfig = Join-Path (Join-Path $env:USERPROFILE ".config") "llmhosts"
if (Test-Path $llmhostsConfig) {
    Remove-Item $llmhostsConfig -Recurse -Force -ErrorAction SilentlyContinue
    Write-Done "Removed $llmhostsConfig"
}

# ── 4. Kill any running llmhosts/ollama processes ────────────
Write-Step "Stopping running processes"

$procs = @("llmhosts", "ollama", "ollama_llama_server")
foreach ($name in $procs) {
    $running = Get-Process -Name $name -ErrorAction SilentlyContinue
    if ($running) {
        $running | Stop-Process -Force -ErrorAction SilentlyContinue
        Write-Done "Stopped $name (PID $($running.Id -join ', '))"
    }
}

# ── 5. Uninstall Ollama ──────────────────────────────────────
if (-not $KeepOllama) {
    Write-Step "Uninstalling Ollama"

    if (Get-Command ollama -ErrorAction SilentlyContinue) {
        $ollamaVer = ollama --version 2>&1
        Write-Host "  Found: $ollamaVer" -ForegroundColor Gray

        # Try winget first
        if (Get-Command winget -ErrorAction SilentlyContinue) {
            Write-Host "  Uninstalling via winget..." -ForegroundColor Gray
            winget uninstall --id Ollama.Ollama --accept-source-agreements --silent 2>&1 | Out-Null
            if ($LASTEXITCODE -eq 0) {
                Write-Done "Ollama uninstalled via winget"
            } else {
                Write-Host "  winget uninstall returned exit code $LASTEXITCODE" -ForegroundColor Yellow
                Write-Host "  Try manually: Settings > Apps > Ollama > Uninstall" -ForegroundColor Yellow
            }
        } else {
            Write-Host '  winget not found - uninstall Ollama manually via Settings > Apps' -ForegroundColor Yellow
        }
    } else {
        Write-Skip "Ollama not installed"
    }

    # Remove Ollama data directory (models, blobs, manifests)
    Write-Step "Removing Ollama data (~/.ollama/)"

    $ollamaDir = Join-Path $env:USERPROFILE ".ollama"
    if (Test-Path $ollamaDir) {
        $size = (Get-ChildItem $ollamaDir -Recurse -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum).Sum
        $sizeGB = [math]::Round($size / 1GB, 2)
        Remove-Item $ollamaDir -Recurse -Force -ErrorAction SilentlyContinue
        Write-Done ("Removed " + $ollamaDir + " (" + $sizeGB + " GB of models)")
    } else {
        Write-Skip '~/.ollama/ does not exist'
    }

    # Also check Ollama AppData location
    $ollamaAppData = Join-Path $env:LOCALAPPDATA "Ollama"
    if (Test-Path $ollamaAppData) {
        Remove-Item $ollamaAppData -Recurse -Force -ErrorAction SilentlyContinue
        Write-Done "Removed $ollamaAppData"
    }

    $ollamaPrograms = Join-Path (Join-Path $env:LOCALAPPDATA "Programs") "Ollama"
    if (Test-Path $ollamaPrograms) {
        Remove-Item $ollamaPrograms -Recurse -Force -ErrorAction SilentlyContinue
        Write-Done "Removed $ollamaPrograms"
    }
} else {
    Write-Skip 'Keeping Ollama (-KeepOllama)'
}

# ── 6. Verify clean state ────────────────────────────────────
Write-Step "Verifying clean state"

$issues = @()

# Check llmhosts gone
$pipCheck = pip list --format=json 2>$null | ConvertFrom-Json -ErrorAction SilentlyContinue
$stillInstalled = $pipCheck | Where-Object { $_.name -eq "llmhosts" }
if ($stillInstalled) { $issues += "llmhosts still in pip" }

# Check llmhosts dir gone
if (Test-Path (Join-Path $env:USERPROFILE ".llmhosts")) { $issues += "~/.llmhosts/ still exists" }

# Check llmhosts command gone
if (Get-Command llmhosts -ErrorAction SilentlyContinue) { $issues += "llmhosts still on PATH" }

if (-not $KeepOllama) {
    if (Get-Command ollama -ErrorAction SilentlyContinue) { $issues += "ollama still on PATH" }
    if (Test-Path (Join-Path $env:USERPROFILE ".ollama")) { $issues += "~/.ollama/ still exists" }
}

# Check Python is still there
$pyOk = $false
try { python --version 2>&1 | Out-Null; $pyOk = $true } catch {}

Write-Host ""
Write-Host "========================================" -ForegroundColor White

if ($issues.Count -eq 0 -and $pyOk) {
    Write-Host "  CLEAN SLATE" -ForegroundColor Green
    Write-Host "  Python: $(python --version 2>&1)" -ForegroundColor DarkGray
    Write-Host "  llmhosts: not installed" -ForegroundColor DarkGray
    if (-not $KeepOllama) {
        Write-Host "  Ollama: not installed" -ForegroundColor DarkGray
    }
    Write-Host "" -ForegroundColor DarkGray
    Write-Host "  Ready for: pip install llmhosts" -ForegroundColor White
    Write-Host "             python -m llmhosts serve --no-tui" -ForegroundColor White
} else {
    if (-not $pyOk) { $issues += "Python not found!" }
    Write-Host "  ISSUES REMAIN:" -ForegroundColor Yellow
    foreach ($issue in $issues) {
        Write-Host "    - $issue" -ForegroundColor Yellow
    }
    Write-Host ""
    Write-Host "  Resolve these before testing." -ForegroundColor Yellow
}

Write-Host "========================================" -ForegroundColor White
Write-Host ""
