#!/bin/bash
echo "=== Testing Ollama connectivity from WSL ==="
echo ""

echo "1. localhost:11434"
if curl -s --max-time 3 http://localhost:11434/api/tags >/dev/null 2>&1; then
    echo "   [OK] Reachable"
    curl -s http://localhost:11434/api/tags | python3 -c "import sys,json; d=json.load(sys.stdin); print(f'   Models: {len(d.get(\"models\",[]))}')" 2>/dev/null
else
    echo "   [FAIL] Not reachable"
fi
echo ""

echo "2. Default gateway (ip route)"
GW=$(ip route show default 2>/dev/null | awk '{print $3}' | head -1)
echo "   IP: ${GW:-not found}"
if [ -n "$GW" ]; then
    if curl -s --max-time 3 "http://${GW}:11434/api/tags" >/dev/null 2>&1; then
        echo "   [OK] Reachable"
        curl -s "http://${GW}:11434/api/tags" | python3 -c "import sys,json; d=json.load(sys.stdin); print(f'   Models: {len(d.get(\"models\",[]))}')" 2>/dev/null
    else
        echo "   [FAIL] Not reachable"
    fi
fi
echo ""

echo "3. resolv.conf nameserver"
NS=$(grep nameserver /etc/resolv.conf 2>/dev/null | awk '{print $2}' | head -1)
echo "   IP: ${NS:-not found}"
if [ -n "$NS" ]; then
    if curl -s --max-time 3 "http://${NS}:11434/api/tags" >/dev/null 2>&1; then
        echo "   [OK] Reachable"
        curl -s "http://${NS}:11434/api/tags" | python3 -c "import sys,json; d=json.load(sys.stdin); print(f'   Models: {len(d.get(\"models\",[]))}')" 2>/dev/null
    else
        echo "   [FAIL] Not reachable"
    fi
fi
echo ""

echo "4. host.docker.internal"
if curl -s --max-time 3 http://host.docker.internal:11434/api/tags >/dev/null 2>&1; then
    echo "   [OK] Reachable"
else
    echo "   [FAIL] Not reachable"
fi
echo ""

echo "5. Windows Ollama binding check"
echo "   Ollama needs OLLAMA_HOST=0.0.0.0 on Windows to listen on all interfaces."
echo "   If only localhost works on Windows but not from WSL, set this env var"
echo "   on Windows and restart Ollama."
echo ""
echo "=== Done ==="
