# verify_podman.ps1
# This script directly tests Windows Named Pipes for Docker/Podman API headers

function Test-PipeConnection {
    param ( [string]$PipeName )
    
    Write-Host "Testing pipe: \\.\pipe\$PipeName ..." -NoNewline
    
    if (-not (Test-Path "\\.\pipe\$PipeName")) {
        Write-Host " NOT FOUND (Skipping)" -ForegroundColor Yellow
        return $false
    }

    try {
        # Create a direct client stream to the pipe
        $pipeClient = New-Object System.IO.Pipes.NamedPipeClientStream(".", $PipeName, [System.IO.Pipes.PipeDirection]::InOut)
        
        # Try to connect with a 1-second timeout
        $pipeClient.Connect(1000)
        
        # Send a raw Docker API Ping
        $writer = New-Object System.IO.StreamWriter($pipeClient)
        $writer.AutoFlush = $true
        # minimal HTTP request to the socket
        $writer.Write("GET /_ping HTTP/1.0`r`n`r`n") 
        
        # Read the response
        $reader = New-Object System.IO.StreamReader($pipeClient)
        $response = $reader.ReadLine() # Read first line (e.g., HTTP/1.1 200 OK)
        
        $pipeClient.Close()

        if ($response -match "OK") {
            Write-Host " SUCCESS! (Server responded: '$response')" -ForegroundColor Green
            return $true
        } else {
            Write-Host " CONNECTED BUT INVALID RESPONSE ('$response')" -ForegroundColor Red
            return $false
        }
    }
    catch {
        Write-Host " CONNECTION FAILED ($($_.Exception.Message))" -ForegroundColor Red
        return $false
    }
}

Write-Host "`n--- Checking Podman Status ---"
$podmanState = (podman machine info --format "{{.Host.MachineState}}" 2>$null)
Write-Host "Podman Machine State: $podmanState"
if ($podmanState -ne "Running") {
    Write-Host "WARNING: Podman machine is not running. Attempting to start..." -ForegroundColor Yellow
    podman machine start
}

Write-Host "`n--- Testing Named Pipes ---"
$found = $false

# List of common pipe names to test
$candidates = @("podman-machine-default", "docker_engine", "podman-machine")

foreach ($name in $candidates) {
    if (Test-PipeConnection -PipeName $name) {
        $found = $true
        $validPipe = "npipe:////./pipe/$name"
        
        Write-Host "`n---------------------------------------------------" -ForegroundColor Cyan
        Write-Host "CONFIRMED CONFIGURATION FOUND" -ForegroundColor Cyan
        Write-Host "Update your mcp-servers.json 'podman' section to:" -ForegroundColor Cyan
        Write-Host "---------------------------------------------------"
        
        $jsonConfig = @"
    "podman": {
        "command": "npx",
        "args": ["-y", "@modelcontextprotocol/server-docker"],
        "env": {
            "DOCKER_HOST": "$validPipe"
        }
    }
"@
        Write-Host $jsonConfig -ForegroundColor White
        break # Stop after finding the first working pipe
    }
}

if (-not $found) {
    Write-Host "`n---------------------------------------------------" -ForegroundColor Red
    Write-Host "NO WORKING PIPES FOUND" -ForegroundColor Red
    Write-Host "---------------------------------------------------"
    Write-Host "Since SSH is available, you may need to use the SSH connection."
    Write-Host "However, MCP servers often struggle with SSH agents on Windows."
    Write-Host "Current SSH URI from podman:"
    podman system connection list --format "{{.URI}}"
}