import os
import requests
import socket
from gemini_api import generate_gemini_response

def _get_target():
    host = os.environ.get("SERVER_HOST") or os.environ.get("OLLAMA_SERVER_HOST")
    port_str = os.environ.get("SERVER_PORT") or os.environ.get("OLLAMA_SERVER_PORT")
    if not host:
        # tenta extrair de OLLAMA_SERVER (ex: http://localhost:5000)
        url = os.environ.get("OLLAMA_SERVER")
        if url:
            try:
                from urllib.parse import urlparse
                p = urlparse(url)
                host = p.hostname or "localhost"
                port_str = port_str or (str(p.port) if p.port else "5000")
            except Exception:
                host = "localhost"
    port = int(port_str) if port_str else 5000
    return host, port

def test_connection():
    print("Testando conexão com o servidor...")
    
    host, port = _get_target()
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(5)
        result = sock.connect_ex((host, port))
        sock.close()
        
        if result == 0:
            print(f"✓ Porta {port} está aberta no host {host}")
        else:
            print(f"✗ Porta {port} não está acessível no host {host}")
            return False
    except Exception as e:
        print(f"✗ Erro ao testar porta: {e}")
        return False
    
    try:
        response = requests.get(f'http://{host}:{port}', timeout=5)
        print(f"✓ Servidor HTTP respondeu com status: {response.status_code}")
    except requests.exceptions.ConnectionError:
        print("✗ Erro de conexão - servidor não está rodando ou não está acessível")
        return False
    except requests.exceptions.Timeout:
        print("✗ Timeout - servidor não respondeu em 5 segundos")
        return False
    except Exception as e:
        print(f"✗ Erro inesperado: {e}")
        return False

    print("\nTestando conexão com Gemini API...")
    test_response = generate_gemini_response("Teste de conexão")
    if isinstance(test_response, str) and test_response.startswith("Error"):
        print(f"✗ Erro na conexão com Gemini API: {test_response}")
        return False
    else:
        preview = (test_response or "").strip()
        preview = preview[:160] + ("..." if len(preview) > 160 else "")
        print("✓ Conexão com Gemini API estabelecida com sucesso")
        print(f"Resposta (preview): {preview}")
        return True

if __name__ == "__main__":
    test_connection() 