# QwenClaw Auto-Start Script
# This script ensures QwenClaw daemon is always running
# Run at Windows startup via Task Scheduler

$ErrorActionPreference = "SilentlyContinue"

$QWENCLAW_DIR = Join-Path $env:USERPROFILE "qwenclaw"
$QWEN_DIR = Join-Path $env:USERPROFILE ".qwen"
$DAEMON_PID_FILE = Join-Path $QWEN_DIR "qwenclaw\daemon.pid"
$LOG_FILE = Join-Path $QWEN_DIR "qwenclaw\autostart.log"

function Write-Log {
    param([string]$Message)
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    "[$timestamp] $Message" | Out-File -FilePath $LOG_FILE -Append
}

Write-Log "QwenClaw auto-start initiated"

# Check if daemon is already running
if (Test-Path $DAEMON_PID_FILE) {
    $pidContent = Get-Content $DAEMON_PID_FILE -ErrorAction SilentlyContinue
    if ($pidContent) {
        try {
            $process = Get-Process -Id ([int]$pidContent) -ErrorAction SilentlyContinue
            if ($process) {
                Write-Log "QwenClaw daemon already running (PID: $pidContent)"
                exit 0
            }
        } catch {
            Write-Log "Stale PID file found, cleaning up..."
            Remove-Item $DAEMON_PID_FILE -Force -ErrorAction SilentlyContinue
        }
    }
}

# Wait for Qwen Code to be available (in case of system startup)
Start-Sleep -Seconds 5

# Start daemon in background
Write-Log "Starting QwenClaw daemon from: $QWENCLAW_DIR"

try {
    $startInfo = New-Object System.Diagnostics.ProcessStartInfo
    $startInfo.FileName = "bun"
    $startInfo.Arguments = "run start --web"
    $startInfo.WorkingDirectory = $QWENCLAW_DIR
    $startInfo.UseShellExecute = $true
    $startInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden
    $startInfo.CreateNoWindow = $true
    
    $process = [System.Diagnostics.Process]::Start($startInfo)
    Write-Log "QwenClaw daemon started (PID: $($process.Id))"
} catch {
    Write-Log "Failed to start daemon: $($_.Exception.Message)"
}

Write-Log "QwenClaw auto-start completed"
