# clauth installer - Windows
# Private repo - run locally:
#   cd C:\Dev\clauth && git pull && .\install.ps1

$ErrorActionPreference = "Stop"
$REPO = "https://github.com/LIFEAI/clauth.git"
$DIR  = "$env:USERPROFILE\.clauth"

# Check git
try { git --version | Out-Null } catch {
    Write-Host ""
    Write-Host "  x git is required." -ForegroundColor Red
    Write-Host "    Install from https://git-scm.com then re-run this script."
    Write-Host ""
    exit 1
}

# Check Node
try { node --version | Out-Null } catch {
    Write-Host ""
    Write-Host "  x Node.js v18+ is required." -ForegroundColor Red
    Write-Host "    Install from https://nodejs.org then re-run this script."
    Write-Host ""
    exit 1
}

# Check cloudflared (soft warning - not required for install)
if (-not (Get-Command cloudflared -ErrorAction SilentlyContinue)) {
    Write-Host "  Note: cloudflared not found. Install after setup for claude.ai web integration." -ForegroundColor Yellow
    Write-Host "        winget install Cloudflare.cloudflared" -ForegroundColor Gray
    Write-Host ""
}

# Skip bootstrap if CLAUTH npm package is already installed globally
$alreadyInstalled = $false
try {
    $ver = & npm list -g @lifeaitools/clauth --depth=0 2>$null | Select-String "@lifeaitools/clauth"
    if ($ver) { $alreadyInstalled = $true }
} catch { }

if ($alreadyInstalled) {
    Write-Host "  clauth already installed globally - skipping bootstrap." -ForegroundColor Green
} else {
    # Clone or update
    if (Test-Path "$DIR\.git") {
        Write-Host "  Updating clauth..."
        Set-Location $DIR; git pull --quiet
    } else {
        Write-Host "  Cloning clauth..."
        git clone --quiet $REPO $DIR
    }

    # Run compiled bootstrap binary
    $bootstrap = "$DIR\scripts\bin\bootstrap-win.exe"
    if (-not (Test-Path $bootstrap)) {
        Write-Host "  x Bootstrap binary not found at $bootstrap" -ForegroundColor Red
        exit 1
    }

    Set-Location $DIR
    & $bootstrap
}

# Register autostart - idempotent, runs every install/update
# Primary: Task Scheduler (preferred - supports delay and OS-managed restarts)
# Fallback: Startup folder shortcut (fully functional - autostart.ps1 has its own crash-recovery loop)
$autostartScript = "$env:APPDATA\clauth\autostart.ps1"
$taskName = "CLAUTH Daemon"

if (Test-Path $autostartScript) {
    Write-Host ""
    Write-Host "  Registering autostart..." -ForegroundColor Cyan

    $registered = $false

    # Try Task Scheduler first
    try {
        Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue
        $action   = New-ScheduledTaskAction -Execute "powershell.exe" `
                      -Argument "-WindowStyle Hidden -ExecutionPolicy Bypass -File `"$autostartScript`""
        $trigger  = New-ScheduledTaskTrigger -AtLogOn
        $settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit 0 -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1)
        Register-ScheduledTask -TaskName $taskName -Action $action -Trigger $trigger `
          -Settings $settings -RunLevel Limited -Force -ErrorAction Stop | Out-Null
        Write-Host "  + Task Scheduler: '$taskName' registered (triggers at logon)." -ForegroundColor Green
        $registered = $true
    } catch { }

    # Fallback: Startup folder - valid solution, autostart.ps1 handles crash recovery internally
    if (-not $registered) {
        $startupDir = "$env:APPDATA\Microsoft\Windows\Start Menu\Programs\Startup"
        $shortcut = "$startupDir\clauth-autostart.lnk"
        $wsh = New-Object -ComObject WScript.Shell
        $lnk = $wsh.CreateShortcut($shortcut)
        $lnk.TargetPath = "powershell.exe"
        # 15s delay baked in so profile is loaded before daemon starts
        $lnk.Arguments = "-WindowStyle Hidden -ExecutionPolicy Bypass -Command `"Start-Sleep 15; & '$autostartScript'`""
        $lnk.WorkingDirectory = "$env:APPDATA\clauth"
        $lnk.WindowStyle = 7
        $lnk.Save()
        Write-Host "  + Autostart registered via Startup folder (15s delay, crash-recovery loop active)." -ForegroundColor Green
    }
} else {
    Write-Host ""
    Write-Host "  ! autostart.ps1 not found - skipping autostart registration." -ForegroundColor Yellow
    Write-Host "    Run: clauth autostart install" -ForegroundColor Gray
}

Write-Host ""
Write-Host "  Installing co-development Windows Terminal profiles..." -ForegroundColor Cyan
try {
    & clauth codevelop install-terminal --repo "C:\Dev\regen-root"
    if ($LASTEXITCODE -eq 0) {
        Write-Host "  + Co-development terminal profiles installed." -ForegroundColor Green
    } else {
        Write-Host "  ! Co-development terminal profile install returned exit code $LASTEXITCODE." -ForegroundColor Yellow
    }
} catch {
    Write-Host "  ! Co-development terminal profile install skipped: $($_.Exception.Message)" -ForegroundColor Yellow
    Write-Host "    Run later: clauth codevelop install-terminal --repo C:\Dev\regen-root" -ForegroundColor Gray
}

exit $LASTEXITCODE
