#!/usr/bin/env python3
"""
Test Simple Everything3 API
Test básico del API Everything3 corregido
"""

import os
import ctypes


def test_simple_everything3():
    """Test simple del API Everything3"""
    dll_path = "Everything-SDK3/dll/Everything3_x64.dll"
    dll_path = os.path.abspath(dll_path)

    print("🔍 Test Simple Everything3 API")
    print(f"📁 DLL: {dll_path}")

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

        # Configurar funciones básicas
        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

        dll.Everything3_CreateSearchState.argtypes = []
        dll.Everything3_CreateSearchState.restype = ctypes.c_void_p

        dll.Everything3_SetSearchTextW.argtypes = [ctypes.c_void_p, ctypes.c_wchar_p]
        dll.Everything3_SetSearchTextW.restype = ctypes.c_bool

        dll.Everything3_Search.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
        dll.Everything3_Search.restype = ctypes.c_void_p

        dll.Everything3_GetResultFullPathNameW.argtypes = [
            ctypes.c_void_p,  # result_list
            ctypes.c_size_t,  # result_index
            ctypes.c_wchar_p,  # buf
            ctypes.c_size_t,  # buf_size_in_wchars
        ]
        dll.Everything3_GetResultFullPathNameW.restype = ctypes.c_size_t

        dll.Everything3_GetResultListCount.argtypes = [ctypes.c_void_p]
        dll.Everything3_GetResultListCount.restype = ctypes.c_size_t

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

        # Conectar
        print("🔌 Conectando...")
        client = dll.Everything3_ConnectW("1.5a")

        if not client:
            error = dll.Everything3_GetLastError()
            print(f"❌ Error conectando: {error}")
            return 0

        print("✅ Conectado")

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

        # Crear search state
        print("🔍 Creando search state...")
        search_state = dll.Everything3_CreateSearchState()

        if not search_state:
            print("❌ No se pudo crear search state")
            return 0

        print("✅ Search state creado")

        # Buscar archivos .s7p
        query = "*.s7p"
        print(f"🔍 Buscando: {query}")

        # Establecer texto de búsqueda
        if not dll.Everything3_SetSearchTextW(search_state, query):
            print("❌ No se pudo establecer texto de búsqueda")
            return 0

        print("✅ Texto de búsqueda establecido")

        # Ejecutar búsqueda
        print("🚀 Ejecutando búsqueda...")
        result_list = dll.Everything3_Search(client, search_state)

        if not result_list:
            error = dll.Everything3_GetLastError()
            print(f"❌ Error en búsqueda: {error}")
            return 0

        print("✅ Búsqueda ejecutada")

        # Obtener número de resultados
        num_results = dll.Everything3_GetResultListCount(result_list)
        print(f"📊 Resultados encontrados: {num_results}")

        # Definir directorios de interés
        target_dirs = [
            "C:\\Users\\migue\\Downloads\\TestBackups",
            "C:/Trabajo/SIDEL/05 - E5.007161 - Modifica O&U - SAE346",
        ]

        # Obtener algunas rutas para verificar
        print("📝 Primeras 10 rutas encontradas:")
        for i in range(min(num_results, 10)):
            buf_size = 32768
            buf = ctypes.create_unicode_buffer(buf_size)

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

            if chars_copied > 0:
                file_path = buf.value
                print(f"  {i+1}. {file_path}")

        # Buscar archivos en directorios objetivo
        matching_files = []
        for i in range(min(num_results, 100)):  # Revisar las primeras 100
            buf_size = 32768
            buf = ctypes.create_unicode_buffer(buf_size)

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

            if chars_copied > 0:
                file_path = buf.value
                # Verificar si está en alguno de los directorios objetivo
                for target_dir in target_dirs:
                    if file_path.lower().startswith(target_dir.lower()):
                        matching_files.append(file_path)
                        break

        print(f"📂 Archivos en directorios objetivo: {len(matching_files)}")
        for file_path in matching_files:
            print(f"  - {file_path}")

        return len(matching_files)

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


if __name__ == "__main__":
    result = test_simple_everything3()
    print(f"🏁 Test completado. Resultados: {result}")
