# SOAGILA Daemon -- zero-touch installer for Windows
#
# Usage (from inside the extracted zip folder):
#     Right-click install.ps1 -> Run with PowerShell
#     (or: powershell -ExecutionPolicy Bypass -File install.ps1)
#
# What it does, silently, with a friendly toast at the end:
#   1. Copies soagila-daemon/ into %LOCALAPPDATA%\Programs\SOAGILA\
#   2. Creates a shortcut in the user's Startup folder so the
#      daemon auto-starts at every logon. No scheduled task, no
#      UAC, no permissions -- pure per-user startup folder entry.
#   3. Installs the Chrome / Edge Native Messaging Host manifest
#      so the browser extension can reach the daemon.
#   4. Starts the daemon immediately in the background
#   5. Shows a Windows toast notification "SOAGILA ready"
#   6. Auto-closes after 2 seconds -- user never sees a log stream
#
# Runs as the normal user. No admin rights, no task scheduler,
# nothing that requires a policy exception. Uninstall is just
# deleting the folder + the shortcut.

param(
    [string]$InstallDir = "$env:LOCALAPPDATA\Programs\SOAGILA",
    [switch]$NoStart,
    [switch]$Verbose
)

$ErrorActionPreference = "Stop"
$here = Split-Path -Parent $MyInvocation.MyCommand.Path

# Minimize the PowerShell window immediately so the install feels
# quiet -- it flashes for half a second then tucks itself away.
if (-not $Verbose) {
    try {
        Add-Type -Name Win -Namespace Console -MemberDefinition '
            [DllImport("Kernel32.dll")] public static extern IntPtr GetConsoleWindow();
            [DllImport("user32.dll")]   public static extern bool   ShowWindow(IntPtr hWnd, int nCmdShow);
        '
        [Console.Win]::ShowWindow([Console.Win]::GetConsoleWindow(), 6) | Out-Null  # 6 = SW_MINIMIZE
    } catch { }
}

function Write-Step($msg) {
    if ($Verbose) { Write-Host $msg -ForegroundColor Cyan }
}

# --- 1. Copy the daemon payload ------------------------------------
Write-Step "[1/4] Copying daemon payload..."

$dest = Join-Path $InstallDir "soagila-daemon"

# If there's a previous install, try to stop any running process
# before we overwrite its files -- otherwise the Remove-Item fails.
try {
    Get-Process -Name "soagila-daemon" -ErrorAction SilentlyContinue |
        Stop-Process -Force -ErrorAction SilentlyContinue
    Start-Sleep -Milliseconds 500
} catch { }

if (Test-Path $dest) {
    Remove-Item -Recurse -Force $dest
}
New-Item -ItemType Directory -Force -Path $dest | Out-Null
$src = Join-Path $here "soagila-daemon"
if (-not (Test-Path $src)) {
    throw "Expected soagila-daemon/ folder next to install.ps1 but not found"
}
Copy-Item -Recurse -Force "$src\*" $dest

$exe = Join-Path $dest "soagila-daemon.exe"
if (-not (Test-Path $exe)) {
    throw "soagila-daemon.exe missing at $exe after copy"
}

# --- 2. Startup folder shortcut (no scheduled task) ----------------
Write-Step "[2/4] Creating Startup shortcut..."

$startup = [Environment]::GetFolderPath("Startup")
if (-not (Test-Path $startup)) {
    New-Item -ItemType Directory -Force -Path $startup | Out-Null
}
$shortcutPath = Join-Path $startup "SOAGILA Daemon.lnk"

# Remove any previous shortcut (idempotent reinstall)
if (Test-Path $shortcutPath) {
    Remove-Item -Force $shortcutPath -ErrorAction SilentlyContinue
}

$wsh = New-Object -ComObject WScript.Shell
$shortcut = $wsh.CreateShortcut($shortcutPath)
$shortcut.TargetPath = $exe
$shortcut.WorkingDirectory = $dest
$shortcut.WindowStyle = 7  # Minimized (safety net -- exe is GUI anyway)
$shortcut.Description = "SOAGILA cognitive memory daemon -- shared local server for VS Code, Desktop, and Browser clients."
$shortcut.Save()

# Also clean up any stale scheduled task from previous versions so
# users upgrading from the old installer don't end up with both.
try {
    schtasks /delete /tn "SOAGILA Daemon" /f 2>&1 | Out-Null
} catch { }

# --- 3. Native messaging host for the browser extension -----------
Write-Step "[3/4] Registering browser native messaging host..."

$nmhScript = Join-Path $dest "native-host\install_windows.ps1"
if (Test-Path $nmhScript) {
    try {
        & $nmhScript -InstallDir $dest | Out-Null
    } catch {
        # Non-fatal -- browser extension falls back to manual login
    }
}

# --- 4. Launch the daemon now -------------------------------------
Write-Step "[4/4] Starting daemon..."

$healthOk = $false
if (-not $NoStart) {
    # Kill any process left from a previous install (just in case)
    try {
        Get-Process -Name "soagila-daemon" -ErrorAction SilentlyContinue |
            Stop-Process -Force -ErrorAction SilentlyContinue
        Start-Sleep -Milliseconds 500
    } catch { }

    # Start the GUI-subsystem exe detached from this shell so it
    # survives after install.ps1 exits.
    Start-Process -FilePath $exe -WorkingDirectory $dest -WindowStyle Hidden
    Start-Sleep -Seconds 3

    # Health check
    $attempts = 0
    while ($attempts -lt 15) {
        try {
            $resp = Invoke-WebRequest -UseBasicParsing -Uri "http://127.0.0.1:19741/health" -TimeoutSec 2
            if ($resp.StatusCode -eq 200) {
                $healthOk = $true
                break
            }
        } catch {
            Start-Sleep -Milliseconds 500
        }
        $attempts++
    }
}

# --- 5. Windows toast notification -- friendly end-state ----------
function Show-Toast($title, $message) {
    try {
        [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType=WindowsRuntime] | Out-Null
        [Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType=WindowsRuntime] | Out-Null

        $xml = @"
<toast activationType="protocol" launch="https://soagila.ai/dashboard/onboarding">
  <visual>
    <binding template="ToastGeneric">
      <text>$title</text>
      <text>$message</text>
    </binding>
  </visual>
</toast>
"@
        $doc = New-Object Windows.Data.Xml.Dom.XmlDocument
        $doc.LoadXml($xml)
        $toast = [Windows.UI.Notifications.ToastNotification]::new($doc)
        $notifier = [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier("SOAGILA")
        $notifier.Show($toast)
    } catch {
        # Fallback: MessageBox
        try {
            Add-Type -AssemblyName System.Windows.Forms
            [System.Windows.Forms.MessageBox]::Show($message, $title, "OK", "Information") | Out-Null
        } catch { }
    }
}

if ($healthOk) {
    Show-Toast "SOAGILA Daemon is running" "Look for the gold S in your system tray. Open soagila.ai/dashboard/onboarding to finish setup."
} else {
    Show-Toast "SOAGILA Daemon installed" "The daemon was registered but didn't respond yet. Check logs at %USERPROFILE%\.soagila\logs\daemon.log"
}

# --- 6. Auto-close -----------------------------------------------
Start-Sleep -Seconds 2