#!/usr/bin/env python3
"""
Debug Everything3 API Connection
Diagnóstico detallado de la conexión con Everything3
"""

import os
import sys
import ctypes
import logging

# Configurar logging
logging.basicConfig(
    level=logging.DEBUG, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)


def debug_everything3_connection():
    """Debuggear la conexión con Everything3"""
    dll_path = "Everything-SDK3/dll/Everything3_x64.dll"
    dll_path = os.path.abspath(dll_path)

    print(f"🔍 Debugging Everything3 Connection")
    print(f"📁 DLL Path: {dll_path}")
    print(f"📁 DLL Exists: {os.path.exists(dll_path)}")

    if not os.path.exists(dll_path):
        print("❌ DLL no encontrada")
        return

    try:
        # Cargar DLL
        dll = ctypes.WinDLL(dll_path)
        print("✅ DLL cargada")

        # Configurar funciones
        dll.Everything3_ConnectW.argtypes = [ctypes.c_wchar_p]
        dll.Everything3_ConnectW.restype = ctypes.c_void_p

        dll.Everything3_GetLastError.argtypes = []
        dll.Everything3_GetLastError.restype = ctypes.c_uint32

        # Intentar conectar con NULL (instancia por defecto)
        print("🔌 Intentando conectar con NULL...")
        client = dll.Everything3_ConnectW(None)
        print(f"Client handle: {client}")

        if client:
            print("✅ Conexión exitosa")
        else:
            error_code = dll.Everything3_GetLastError()
            print(f"❌ Conexión falló: {error_code} (0x{error_code:08x})")

            # Convertir a códigos conocidos
            error_names = {
                0xE0000001: "EVERYTHING3_ERROR_OUT_OF_MEMORY",
                0xE0000002: "EVERYTHING3_ERROR_IPC_PIPE_NOT_FOUND",
                0xE0000003: "EVERYTHING3_ERROR_DISCONNECTED",
                0xE0000004: "EVERYTHING3_ERROR_INVALID_PARAMETER",
                0xE0000005: "EVERYTHING3_ERROR_BAD_REQUEST",
                0xE0000006: "EVERYTHING3_ERROR_CANCELLED",
                0xE0000007: "EVERYTHING3_ERROR_PROPERTY_NOT_FOUND",
                0xE0000008: "EVERYTHING3_ERROR_SERVER",
                0xE0000009: "EVERYTHING3_ERROR_INVALID_COMMAND",
                0xE000000A: "EVERYTHING3_ERROR_BAD_RESPONSE",
                0xE000000B: "EVERYTHING3_ERROR_INSUFFICIENT_BUFFER",
                0xE000000C: "EVERYTHING3_ERROR_SHUTDOWN",
                0xE000000D: "EVERYTHING3_ERROR_INVALID_PROPERTY_VALUE_TYPE",
            }

            error_name = error_names.get(error_code, "UNKNOWN_ERROR")
            print(f"Error: {error_name}")

            if error_code == 0xE0000002:
                print(
                    "💡 Esto indica que Everything no está ejecutándose o el IPC pipe no está disponible"
                )

        # Intentar conectar con "1.5a"
        print("\n🔌 Intentando conectar con '1.5a'...")
        client2 = dll.Everything3_ConnectW("1.5a")
        print(f"Client handle: {client2}")

        if client2:
            print("✅ Conexión con '1.5a' exitosa")
        else:
            error_code2 = dll.Everything3_GetLastError()
            print(f"❌ Conexión con '1.5a' falló: {error_code2} (0x{error_code2:08x})")
            error_name2 = error_names.get(error_code2, "UNKNOWN_ERROR")
            print(f"Error: {error_name2}")

    except Exception as e:
        print(f"❌ Error: {e}")


if __name__ == "__main__":
    debug_everything3_connection()
