#!/usr/bin/env python3
"""
Test Everything API Status
Script para verificar el estado de la API de Everything sin usar fallback
"""

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))

# Imports del proyecto
from models.config_model import Config
from models.project_model import ProjectManager
from services.project_discovery_service import ProjectDiscoveryService


def print_section(title):
    """Imprimir una sección con formato"""
    print(f"\n{'='*60}")
    print(f" {title}")
    print(f"{'='*60}")


def print_status_item(label, value, status=None):
    """Imprimir un item de estado con formato"""
    if status is None:
        status = "✅" if value else "❌"
    print(f"{status} {label}: {value}")


def main():
    """Función principal"""
    print_section("VERIFICACIÓN DE EVERYTHING API - SIN FALLBACK")

    try:
        # Cargar configuración
        print("📋 Cargando configuración...")
        config = Config()
        print("✅ Configuración cargada")

        # Inicializar Project Manager
        print("📁 Inicializando Project Manager...")
        project_manager = ProjectManager()
        print("✅ Project Manager inicializado")

        # Inicializar Project Discovery Service
        print("🔍 Inicializando Project Discovery Service...")
        discovery_service = ProjectDiscoveryService(config, project_manager)
        print("✅ Project Discovery Service inicializado")

        # Verificar estado de Everything API
        print_section("ESTADO DE EVERYTHING API")
        status = discovery_service.check_everything_api_status()

        print_status_item("Habilitado en configuración", status["enabled_in_config"])
        print_status_item("Ruta DLL", status["dll_path"], "📄")
        print_status_item("DLL existe", status["dll_exists"])
        print_status_item("Searcher inicializado", status["searcher_initialized"])
        print_status_item("Everything disponible", status["everything_available"])

        if status["error_message"]:
            print_status_item("Error", status["error_message"], "❌")

        # Mostrar diagnóstico detallado si está disponible
        if status["everything_diagnosis"]:
            print_section("DIAGNÓSTICO DETALLADO")
            diagnosis = status["everything_diagnosis"]

            for key, value in diagnosis.items():
                if key == "exception":
                    print_status_item("Excepción", value, "⚠️")
                else:
                    formatted_key = key.replace("_", " ").title()
                    print_status_item(formatted_key, value, "ℹ️")

        # Test de búsqueda si Everything está disponible
        if status["everything_available"]:
            print_section("TEST DE BÚSQUEDA")
            print("🔍 Ejecutando test de búsqueda de archivos .s7p...")

            test_result = discovery_service.test_everything_api_search()

            print_status_item("Test exitoso", test_result["success"])
            print_status_item("Consulta", test_result["test_query"], "📝")
            print_status_item(
                "Archivos encontrados", test_result["results_count"], "📊"
            )
            print_status_item(
                "Tiempo de ejecución (ms)", test_result["execution_time_ms"], "⏱️"
            )

            if test_result["error_message"]:
                print_status_item("Error en test", test_result["error_message"], "❌")

            # Mostrar algunos resultados
            if test_result["results"]:
                print("\n📋 Primeros resultados encontrados:")
                for i, result in enumerate(test_result["results"][:5], 1):
                    print(f"   {i}. {result}")

                if test_result["results_count"] > 5:
                    remaining = test_result["results_count"] - 5
                    print(f"   ... y {remaining} más")

        # Test de descubrimiento sin fallback
        print_section("TEST DE DESCUBRIMIENTO SIN FALLBACK")
        print("🔍 Ejecutando descubrimiento usando SOLO Everything API...")

        all_projects = []
        observation_dirs = [
            obs_dir
            for obs_dir in config.observation_directories
            if (obs_dir.get("enabled", True) and obs_dir.get("type") == "siemens_s7")
        ]

        if not observation_dirs:
            print("⚠️  No hay directorios de observación de Siemens S7")
        else:
            for obs_dir in observation_dirs:
                print(f"📁 Escaneando: {obs_dir['path']}")
                projects = discovery_service.discover_s7_projects_everything_only(
                    obs_dir
                )
                all_projects.extend(projects)
                print(f"   ✅ Encontrados {len(projects)} proyectos")

        print_status_item("Total de proyectos encontrados", len(all_projects), "📊")

        # Mostrar algunos proyectos
        if all_projects:
            print("\n📋 Proyectos encontrados:")
            for i, project in enumerate(all_projects[:5], 1):
                print(f"   {i}. {project.name} ({project.path})")

            if len(all_projects) > 5:
                remaining = len(all_projects) - 5
                print(f"   ... y {remaining} más")

        print_section("RESUMEN")

        if status["everything_available"]:
            print("✅ Everything API está funcionando correctamente")
            projects_count = len(all_projects)
            print(f"📊 Se encontraron {projects_count} proyectos sin fallback")
        else:
            print("❌ Everything API no está disponible")
            if not status["enabled_in_config"]:
                print("💡 Sugerencia: Habilitar Everything API en config")
            elif not status["dll_exists"]:
                print("💡 Sugerencia: Verificar que el DLL existe")
            elif not status["searcher_initialized"]:
                print("💡 Sugerencia: Verificar inicialización del searcher")
            else:
                print("💡 Sugerencia: Verificar que Everything esté ejecutándose")

    except Exception as e:
        print(f"\n❌ Error durante la verificación: {e}")
        return 1

    return 0


if __name__ == "__main__":
    sys.exit(main())

    # Test without Everything API
    print("2. Testing WITHOUT Everything API:")
    print("-" * 40)

    config.set("everything_api.enabled", False)
    discovery_service = ProjectDiscoveryService(config, project_manager)

    start_time = time.time()
    projects_without_api = discovery_service.discover_projects()
    time_without_api = time.time() - start_time

    print(f"Found {len(projects_without_api)} projects in {time_without_api:.2f}s")
    for project in projects_without_api[:5]:  # Show first 5 projects
        print(f"  - {project.name} ({project.type}) at {project.path}")
    if len(projects_without_api) > 5:
        print(f"  ... and {len(projects_without_api) - 5} more projects")
    print()

    # Compare results
    print("3. COMPARISON:")
    print("-" * 40)
    print(f"Projects with API:    {len(projects_with_api)}")
    print(f"Projects without API: {len(projects_without_api)}")
    print(f"Time with API:        {time_with_api:.2f}s")
    print(f"Time without API:     {time_without_api:.2f}s")

    if time_with_api > 0 and time_without_api > 0:
        speedup = time_without_api / time_with_api
        print(f"Speed improvement:    {speedup:.2f}x")

    # Check if projects are the same
    paths_with_api = set(p.path for p in projects_with_api)
    paths_without_api = set(p.path for p in projects_without_api)

    missing_with_api = paths_without_api - paths_with_api
    extra_with_api = paths_with_api - paths_without_api

    if missing_with_api:
        print(f"\nProjects MISSING when using API ({len(missing_with_api)}):")
        for path in sorted(missing_with_api)[:10]:
            print(f"  - {path}")
        if len(missing_with_api) > 10:
            print(f"  ... and {len(missing_with_api) - 10} more")

    if extra_with_api:
        print(f"\nEXTRA projects when using API ({len(extra_with_api)}):")
        for path in sorted(extra_with_api)[:10]:
            print(f"  - {path}")
        if len(extra_with_api) > 10:
            print(f"  ... and {len(extra_with_api) - 10} more")

    if not missing_with_api and not extra_with_api:
        print("\n✅ SAME projects found with both methods!")
    elif len(missing_with_api) == 0 and len(extra_with_api) == 0:
        print("\n✅ IDENTICAL results with both methods!")
    else:
        msg = (
            f"\n⚠️  DIFFERENT results: {len(missing_with_api)} missing, "
            f"{len(extra_with_api)} extra with API"
        )
        print(msg)

    return {
        "with_api": len(projects_with_api),
        "without_api": len(projects_without_api),
        "time_with_api": time_with_api,
        "time_without_api": time_without_api,
        "missing_with_api": len(missing_with_api),
        "extra_with_api": len(extra_with_api),
    }


if __name__ == "__main__":
    try:
        results = test_project_discovery()
    except Exception as e:
        print(f"❌ Error during testing: {e}")
        import traceback

        traceback.print_exc()
        sys.exit(1)
