# Mosaic Bootstrap — Windows Installer
# PowerShell equivalent of install.sh
#
# Usage:
#   powershell -ExecutionPolicy Bypass -File install.ps1
#
$ErrorActionPreference = "Stop"

$SourceDir = $PSScriptRoot
$TargetDir = if ($env:MOSAIC_HOME) { $env:MOSAIC_HOME } else { Join-Path $env:USERPROFILE ".config\mosaic" }
$InstallMode = if ($env:MOSAIC_INSTALL_MODE) { $env:MOSAIC_INSTALL_MODE.ToLowerInvariant() } else { "prompt" } # prompt|keep|overwrite
$PreservePaths = @("SOUL.md", "memory")

function Write-Ok   { param([string]$Msg) Write-Host "  ✓ " -ForegroundColor Green -NoNewline; Write-Host $Msg }
function Write-Warn { param([string]$Msg) Write-Host "  ⚠ " -ForegroundColor Yellow -NoNewline; Write-Host $Msg }
function Write-Fail { param([string]$Msg) Write-Host "  ✗ " -ForegroundColor Red -NoNewline; Write-Host $Msg }
function Write-Step { param([string]$Msg) Write-Host ""; Write-Host $Msg -ForegroundColor White -BackgroundColor DarkGray }

function Test-ExistingInstall {
    if (-not (Test-Path $TargetDir)) { return $false }
    return (Test-Path (Join-Path $TargetDir "bin\mosaic")) -or (Test-Path (Join-Path $TargetDir "AGENTS.md")) -or (Test-Path (Join-Path $TargetDir "SOUL.md"))
}

function Select-InstallMode {
    switch ($InstallMode) {
        "prompt" { }
        "keep" { return }
        "overwrite" { return }
        default {
            Write-Fail "Invalid MOSAIC_INSTALL_MODE '$InstallMode'. Use: prompt, keep, overwrite."
            exit 1
        }
    }

    if (-not (Test-ExistingInstall)) {
        $script:InstallMode = "overwrite"
        return
    }

    if (-not [Environment]::UserInteractive) {
        Write-Warn "Existing install detected without interactive input; defaulting to keep local files."
        $script:InstallMode = "keep"
        return
    }

    Write-Host ""
    Write-Host "Existing Mosaic install detected at: $TargetDir"
    Write-Host "Choose reinstall mode:"
    Write-Host "  1) keep      Keep local files (SOUL.md, memory/) while updating framework"
    Write-Host "  2) overwrite Replace everything in $TargetDir"
    Write-Host "  3) cancel    Abort install"
    $selection = Read-Host "Selection [1/2/3] (default: 1)"

    $normalizedSelection = if ($null -eq $selection) { "" } else { $selection.ToLowerInvariant() }
    switch ($normalizedSelection) {
        "" { $script:InstallMode = "keep" }
        "1" { $script:InstallMode = "keep" }
        "k" { $script:InstallMode = "keep" }
        "keep" { $script:InstallMode = "keep" }
        "2" { $script:InstallMode = "overwrite" }
        "o" { $script:InstallMode = "overwrite" }
        "overwrite" { $script:InstallMode = "overwrite" }
        "3" { Write-Fail "Install cancelled."; exit 1 }
        "c" { Write-Fail "Install cancelled."; exit 1 }
        "cancel" { Write-Fail "Install cancelled."; exit 1 }
        default {
            Write-Warn "Unrecognized selection '$selection'; defaulting to keep."
            $script:InstallMode = "keep"
        }
    }
}

# ── Install framework ────────────────────────────────────────
Write-Step " Installing Mosaic framework "

if (-not (Test-Path $TargetDir)) { New-Item -ItemType Directory -Path $TargetDir -Force | Out-Null }
Select-InstallMode

if ($InstallMode -eq "keep") {
    Write-Ok "Install mode: keep local SOUL.md/memory while updating framework"
}
else {
    Write-Ok "Install mode: overwrite existing files"
}

$preserveTmp = $null
if ($InstallMode -eq "keep") {
    $preserveTmp = Join-Path ([System.IO.Path]::GetTempPath()) ("mosaic-preserve-" + [Guid]::NewGuid().ToString("N"))
    New-Item -ItemType Directory -Path $preserveTmp -Force | Out-Null
    foreach ($relPath in $PreservePaths) {
        $src = Join-Path $TargetDir $relPath
        if (Test-Path $src) {
            $dstParent = Join-Path $preserveTmp (Split-Path $relPath -Parent)
            if (-not [string]::IsNullOrEmpty($dstParent) -and -not (Test-Path $dstParent)) {
                New-Item -ItemType Directory -Path $dstParent -Force | Out-Null
            }
            Copy-Item $src (Join-Path $preserveTmp $relPath) -Recurse -Force
        }
    }
}

Get-ChildItem $TargetDir -Exclude ".git" | Remove-Item -Recurse -Force
Get-ChildItem $SourceDir -Exclude ".git" | ForEach-Object {
    $dest = Join-Path $TargetDir $_.Name
    if ($_.PSIsContainer) {
        Copy-Item $_.FullName $dest -Recurse -Force
    }
    else {
        Copy-Item $_.FullName $dest -Force
    }
}

if ($InstallMode -eq "keep" -and $null -ne $preserveTmp) {
    foreach ($relPath in $PreservePaths) {
        $src = Join-Path $preserveTmp $relPath
        if (Test-Path $src) {
            $dst = Join-Path $TargetDir $relPath
            if (Test-Path $dst) {
                Remove-Item $dst -Recurse -Force
            }
            $dstParent = Split-Path $dst -Parent
            if (-not (Test-Path $dstParent)) {
                New-Item -ItemType Directory -Path $dstParent -Force | Out-Null
            }
            Copy-Item $src $dst -Recurse -Force
        }
    }
    Remove-Item -Path $preserveTmp -Recurse -Force -ErrorAction SilentlyContinue
}

Write-Ok "Framework installed to $TargetDir"

# ── Post-install tasks ───────────────────────────────────────
Write-Step " Post-install tasks "

$binDir = Join-Path $TargetDir "bin"

try {
    & "$binDir\mosaic-link-runtime-assets.ps1" *>$null
    Write-Ok "Runtime assets linked"
}
catch {
    Write-Warn "Runtime asset linking failed (non-fatal)"
}

try {
    & "$binDir\mosaic-ensure-sequential-thinking.ps1" *>$null
    Write-Ok "sequential-thinking MCP configured"
}
catch {
    if ($env:MOSAIC_ALLOW_MISSING_SEQUENTIAL_THINKING -eq "1") {
        Write-Warn "sequential-thinking MCP setup failed but bypassed (MOSAIC_ALLOW_MISSING_SEQUENTIAL_THINKING=1)"
    }
    else {
        Write-Fail "sequential-thinking MCP setup failed (hard requirement)."
        Write-Fail "Set MOSAIC_ALLOW_MISSING_SEQUENTIAL_THINKING=1 only for temporary bypass scenarios."
        exit 1
    }
}

if ($env:MOSAIC_SKIP_SKILLS_SYNC -eq "1") {
    Write-Ok "Skills sync skipped (MOSAIC_SKIP_SKILLS_SYNC=1)"
}
else {
    try {
        & "$binDir\mosaic-sync-skills.ps1" *>$null
        Write-Ok "Skills synced"
    }
    catch {
        Write-Warn "Skills sync failed (non-fatal)"
    }
}

try {
    & "$binDir\mosaic-migrate-local-skills.ps1" -Apply *>$null
    Write-Ok "Local skills migrated"
}
catch {
    Write-Warn "Local skill migration failed (non-fatal)"
}

try {
    & "$binDir\mosaic-doctor.ps1" *>$null
    Write-Ok "Health audit passed"
}
catch {
    Write-Warn "Health audit reported issues — run 'mosaic doctor' for details"
}

# ── PATH configuration ───────────────────────────────────────
Write-Step " PATH configuration "

$mosaicBin = Join-Path $TargetDir "bin"
$userPath = [Environment]::GetEnvironmentVariable("Path", "User")
$pathChanged = $false

if ($userPath -and $userPath.Split(";") -contains $mosaicBin) {
    Write-Ok "Already in User PATH"
}
else {
    $newPath = if ($userPath) { "$mosaicBin;$userPath" } else { $mosaicBin }
    [Environment]::SetEnvironmentVariable("Path", $newPath, "User")
    $env:Path = "$mosaicBin;$env:Path"
    Write-Ok "Added to User PATH"
    $pathChanged = $true
}

# ── Summary ──────────────────────────────────────────────────
Write-Host ""
Write-Host "  Mosaic installed successfully." -ForegroundColor Green
Write-Host ""

$nextSteps = @()

if ($pathChanged) {
    $nextSteps += "Open a new terminal (or log out and back in) to activate PATH."
}

$soulPath = Join-Path $TargetDir "SOUL.md"
if (-not (Test-Path $soulPath)) {
    $nextSteps += "Run 'mosaic init' to set up your agent identity (SOUL.md)."
}

if ($nextSteps.Count -gt 0) {
    Write-Host "  Next steps:" -ForegroundColor White
    for ($i = 0; $i -lt $nextSteps.Count; $i++) {
        Write-Host "  $($i + 1). " -NoNewline
        Write-Host $nextSteps[$i] -ForegroundColor Cyan
    }
    Write-Host ""
}
