# Chrome DevTools MCP Lock Recovery Script
# Finds and kills only Chrome processes using the MCP profile directory.
# NEVER kills the user's personal browser — only targets mcp-profile processes.
#
# Usage (from bash):
#   powershell -ExecutionPolicy Bypass -File chrome-lock-recover.ps1
#
# When to use:
#   navigate_page fails with "The browser is already running for ..."

$killed = 0
Get-CimInstance Win32_Process -Filter "Name='chrome.exe'" | ForEach-Object {
    if ($_.CommandLine -like '*chrome-mcp*' -or $_.CommandLine -like '*mcp-profile*') {
        Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue
        $killed++
    }
}

# Wait for processes to fully exit
if ($killed -gt 0) { Start-Sleep -Seconds 2 }

# Clean up lock files
$profiles = @(
    "$env:USERPROFILE\.cache\chrome-devtools-mcp\chrome-profile",
    "$env:USERPROFILE\.chrome-mcp-profile2"
)
foreach ($p in $profiles) {
    foreach ($lock in @('SingletonLock', 'lockfile')) {
        $f = Join-Path $p $lock
        if (Test-Path $f) {
            Remove-Item -Force $f -ErrorAction SilentlyContinue
        }
    }
}

# Verify
$remaining = 0
Get-CimInstance Win32_Process -Filter "Name='chrome.exe'" | ForEach-Object {
    if ($_.CommandLine -like '*chrome-mcp*' -or $_.CommandLine -like '*mcp-profile*') {
        $remaining++
    }
}

Write-Output "Killed $killed processes"
Write-Output "Remaining: $remaining"
