#!/usr/bin/env python3
"""
Test Everything3 con búsqueda específica por directorios
"""

import os
import ctypes


def test_everything3_specific_paths():
    """Test específico para los directorios objetivo"""
    dll_path = "Everything-SDK3/dll/Everything3_x64.dll"
    dll_path = os.path.abspath(dll_path)

    print("🔍 Test Everything3 - Búsqueda Específica")

    # Directorios objetivo
    target_dirs = [
        "C:\\Users\\migue\\Downloads\\TestBackups",
        "C:\\Trabajo\\SIDEL\\05 - E5.007161 - Modifica O&U - SAE346",
    ]

    try:
        # Cargar DLL
        dll = ctypes.WinDLL(dll_path)

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

        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_GetResultListCount.argtypes = [ctypes.c_void_p]
        dll.Everything3_GetResultListCount.restype = ctypes.c_size_t

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

        # Conectar
        client = dll.Everything3_ConnectW("1.5a")
        if not client:
            print("❌ No se pudo conectar")
            return 0

        total_found = 0

        # Buscar en cada directorio específicamente
        for target_dir in target_dirs:
            print(f"\n📂 Buscando en: {target_dir}")

            # Crear search state
            search_state = dll.Everything3_CreateSearchState()
            if not search_state:
                continue

            # Construir query específica para el directorio
            # Usar comillas para manejar espacios en rutas
            query = f'*.s7p path:"{target_dir}"'
            print(f"🔍 Query: {query}")

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

            # Ejecutar búsqueda
            result_list = dll.Everything3_Search(client, search_state)
            if not result_list:
                print("❌ Búsqueda falló")
                continue

            # Obtener resultados
            num_results = dll.Everything3_GetResultListCount(result_list)
            print(f"📊 Resultados en este directorio: {num_results}")

            # Mostrar rutas encontradas
            for i in range(num_results):
                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}")

            total_found += num_results

        print(f"\n🏁 Total archivos encontrados: {total_found}")
        print(
            f"📈 ¿Se encontraron los 9 proyectos esperados? {'✅ SÍ' if total_found == 9 else '❌ NO'}"
        )

        return total_found

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


if __name__ == "__main__":
    result = test_everything3_specific_paths()
