@echo off
setlocal

if "%~1"=="" (
    echo Usage: find_claude.bat ^<psmux-session-name^>
    exit /b 1
)

set "PS_SCRIPT=%TEMP%\find_claude_%RANDOM%.ps1"

>"%PS_SCRIPT%" (
    echo $procs = Get-CimInstance Win32_Process
    echo $srv = $procs ^| Where-Object { $_.Name -match 'psmux' -and $_.CommandLine -match 'server\s+-s\s+%~1' } ^| Select-Object -First 1
    echo if (-not $srv^) { exit 1 }
    echo # Walk descendants breadth-first looking for claude
    echo $queue = [System.Collections.Queue]::new(^)
    echo $queue.Enqueue($srv.ProcessId^)
    echo while ($queue.Count -gt 0^) {
    echo     $pid_ = $queue.Dequeue(^)
    echo     $children = $procs ^| Where-Object { $_.ParentProcessId -eq $pid_ }
    echo     foreach ($c in $children^) {
    echo         if ($c.Name -match 'claude'^) { $c.ProcessId; exit 0 }
    echo         $queue.Enqueue($c.ProcessId^)
    echo     }
    echo }
    echo exit 1
)

for /f %%p in ('powershell -NoProfile -ExecutionPolicy Bypass -File "%PS_SCRIPT%"') do set "CLAUDE_PID=%%p"
del "%PS_SCRIPT%" 2>nul

if defined CLAUDE_PID (
    echo %CLAUDE_PID%
) else (
    echo No claude process found in psmux session "%~1"
    exit /b 1
)
