#!/usr/bin/env python3
"""
Test Everything3 API con metodología correcta
"""

import ctypes
import os
import sys
from pathlib import Path

# Agregar el directorio src al path
current_dir = Path(__file__).parent
src_dir = current_dir / "src"
sys.path.insert(0, str(src_dir))


def test_everything3_correct():
    """Test de Everything3 API usando la metodología correcta"""

    dll_path = "Everything-SDK3/dll/Everything3_x64.dll"

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

    print(f"✅ Cargando DLL: {dll_path}")

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

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

        dll.Everything3_IsDBLoaded.argtypes = [ctypes.c_void_p]
        dll.Everything3_IsDBLoaded.restype = ctypes.c_bool

        # Usar SetSearchW y QueryW en lugar de Search
        dll.Everything3_SetSearchW.argtypes = [ctypes.c_void_p, ctypes.c_wchar_p]
        dll.Everything3_SetSearchW.restype = None

        dll.Everything3_QueryW.argtypes = [ctypes.c_void_p, ctypes.c_bool]
        dll.Everything3_QueryW.restype = ctypes.c_bool

        # Usar GetNumResults en lugar de GetResults
        dll.Everything3_GetNumResults.argtypes = [ctypes.c_void_p]
        dll.Everything3_GetNumResults.restype = ctypes.c_uint32

        dll.Everything3_GetResultFullPathNameW.argtypes = [
            ctypes.c_void_p,
            ctypes.c_uint32,
            ctypes.c_wchar_p,
            ctypes.c_uint32,
        ]
        dll.Everything3_GetResultFullPathNameW.restype = ctypes.c_uint32

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

        print("✅ Funciones configuradas")

        # Conectar
        client = dll.Everything3_ConnectW("1.5a")
        if not client or client == 0:
            print("❌ Falló la conexión")
            return

        print(f"✅ Conectado (client: {hex(client)})")

        # Verificar DB
        db_loaded = dll.Everything3_IsDBLoaded(client)
        print(f"📋 DB cargada: {db_loaded}")

        # Test consultas usando SetSearchW + QueryW
        test_queries = [
            "*.s7p",
            "ext:s7p",
            'ext:s7p folder:"C:\\Users\\migue\\Downloads\\TestBackups"',
        ]

        for query in test_queries:
            print(f"\n🔍 Probando consulta: {query}")

            try:
                # Establecer búsqueda
                dll.Everything3_SetSearchW(client, query)
                print("✅ Búsqueda establecida")

                # Ejecutar consulta
                query_success = dll.Everything3_QueryW(client, True)

                if query_success:
                    num_results = dll.Everything3_GetNumResults(client)
                    print(f"✅ Éxito: {num_results} resultados")

                    if num_results > 0:
                        print(f"🎉 ¡Encontrados {num_results} archivos!")

                        # Obtener primeros 5 resultados
                        for i in range(min(num_results, 5)):
                            buf_size = 4096
                            buf = ctypes.create_unicode_buffer(buf_size)

                            chars_copied = dll.Everything3_GetResultFullPathNameW(
                                client, i, buf, buf_size
                            )

                            if chars_copied > 0:
                                print(f"   {i+1}. {buf.value}")
                            else:
                                print(f"   {i+1}. Error obteniendo ruta")

                        if query == "*.s7p":
                            break  # Encontramos archivos .s7p, podemos parar
                else:
                    error_code = dll.Everything3_GetLastError(client)
                    print(f"❌ Error en consulta: {error_code}")

            except Exception as e:
                print(f"❌ Excepción en búsqueda: {e}")

        print("\n✅ Test completado")

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


if __name__ == "__main__":
    test_everything3_correct()
