#!/usr/bin/env python3
"""
Everything API Auto Detector
Detecta automáticamente qué wrapper de Everything usar
"""

import os
import logging
from typing import Optional, Union
from pathlib import Path

from .everything_wrapper import EverythingSearcher
from .everything3_official_corrected_wrapper import create_everything3_official_searcher


logger = logging.getLogger(__name__)


def detect_everything_version(dll_path: str) -> str:
    """
    Detecta qué versión de Everything API está disponible
    """
    dll_path = Path(dll_path)

    if "Everything3" in str(dll_path):
        return "everything3"
    elif "Everything64" in str(dll_path) or "Everything32" in str(dll_path):
        return "everything2"
    elif dll_path.exists():
        # Detectar por contenido del archivo si es necesario
        return "everything2"  # Default
    else:
        return "unknown"


def create_everything_searcher_auto(
    dll_path: str,
) -> Optional[Union[EverythingSearcher, object]]:
    """
    Crear automáticamente el searcher apropiado según la DLL disponible
    """
    try:
        if not dll_path or not os.path.exists(dll_path):
            logger.warning(f"DLL path no existe: {dll_path}")
            return None

        version = detect_everything_version(dll_path)
        logger.info(f"Detectada versión de Everything: {version}")

        if version == "everything3":
            logger.info("Usando Everything3 Working Wrapper")
            searcher = create_everything3_official_searcher(dll_path)
            if searcher:
                return searcher
            else:
                logger.error("No se pudo inicializar Everything3 Working Searcher")
                return None
        elif version == "everything2":
            logger.info("Usando Everything2 Wrapper")
            searcher = EverythingSearcher(dll_path)
            if searcher.is_everything_available():
                return searcher
            else:
                logger.error("Everything2 no está disponible")
                return None
        else:
            logger.error(f"Versión de Everything no soportada: {version}")
            return None

    except Exception as e:
        logger.error(f"Error creando Everything searcher automático: {e}")
        return None


class UniversalEverythingSearcher:
    """
    Wrapper universal que funciona con cualquier versión de Everything
    """

    def __init__(self, dll_path: str):
        self.dll_path = dll_path
        self.searcher = None
        self.version = None
        self.logger = logging.getLogger(__name__)

        self._initialize_searcher()

    def _initialize_searcher(self):
        """Inicializar el searcher apropiado"""
        self.searcher = create_everything_searcher_auto(self.dll_path)
        if self.searcher:
            self.version = detect_everything_version(self.dll_path)
            self.logger.info(
                f"Everything searcher inicializado (versión: {self.version})"
            )
        else:
            self.logger.error("No se pudo inicializar ningún Everything searcher")

    def is_everything_available(self) -> bool:
        """Verificar si Everything está disponible"""
        if not self.searcher:
            return False

        if self.version == "everything3":
            # Para Everything3, verificar si está inicializado
            return (
                hasattr(self.searcher, "_is_initialized")
                and self.searcher._is_initialized
            )
        elif self.version == "everything2":
            return self.searcher.is_everything_available()
        else:
            return False

    def search_s7p_files(self, search_directories: list) -> list:
        """Buscar archivos .s7p en los directorios especificados"""
        if not self.searcher:
            self.logger.error("Searcher no inicializado")
            return []

        try:
            if self.version == "everything3":
                return self._search_s7p_everything3(search_directories)
            elif self.version == "everything2":
                return self.searcher.search_s7p_files(search_directories)
            else:
                self.logger.error(f"Versión no soportada para búsqueda: {self.version}")
                return []
        except Exception as e:
            self.logger.error(f"Error en búsqueda S7P: {e}")
            return []

    def _search_s7p_everything3(self, search_directories: list) -> list:
        """Buscar archivos .s7p usando Everything3"""
        results = []

        if not hasattr(self.searcher, "search_s7p_files"):
            self.logger.error("Everything3 searcher no tiene método search_s7p_files")
            return results

        try:
            # Usar el método search_s7p_files del searcher
            results = self.searcher.search_s7p_files(search_directories)
        except Exception as e:
            self.logger.error(f"Error usando search_s7p_files: {e}")

        return results

    def get_everything_diagnosis(self) -> dict:
        """Obtener diagnóstico del estado de Everything"""
        diagnosis = {
            "searcher_type": self.version,
            "dll_path": self.dll_path,
            "dll_exists": (os.path.exists(self.dll_path) if self.dll_path else False),
            "searcher_initialized": self.searcher is not None,
            "everything_available": self.is_everything_available(),
        }

        # Agregar diagnóstico específico según la versión
        if self.searcher and self.version == "everything2":
            if hasattr(self.searcher, "get_everything_diagnosis"):
                diagnosis.update(self.searcher.get_everything_diagnosis())
        elif self.searcher and self.version == "everything3":
            diagnosis["everything3_client"] = (
                hasattr(self.searcher, "client") and self.searcher.client is not None
            )

        return diagnosis


def create_universal_everything_searcher(
    dll_path: str,
) -> Optional[UniversalEverythingSearcher]:
    """
    Crear un searcher universal que detecta automáticamente la versión
    """
    try:
        searcher = UniversalEverythingSearcher(dll_path)
        if searcher.is_everything_available():
            return searcher
        else:
            logger.warning("Universal Everything searcher no está disponible")
            return None
    except Exception as e:
        logger.error(f"Error creando Universal Everything searcher: {e}")
        return None
