"""
Explorador de la API real del paquete siemens_tiaportal_scripting instalado
Descubre qué está realmente disponible
"""

def explore_actual_api():
    """Explore what's actually available in the installed package."""
    
    print("="*70)
    print("EXPLORADOR DE LA API REAL INSTALADA")
    print("="*70)
    
    try:
        import siemens_tiaportal_scripting as ts
        print("✅ Paquete importado correctamente")
        
        # Get all available attributes
        all_attrs = dir(ts)
        public_attrs = [attr for attr in all_attrs if not attr.startswith('_')]
        
        print(f"\n📋 TODOS LOS ATRIBUTOS DISPONIBLES ({len(public_attrs)}):")
        for i, attr in enumerate(sorted(public_attrs), 1):
            try:
                obj = getattr(ts, attr)
                obj_type = type(obj).__name__
                print(f"   {i:2d}. {attr:<25} : {obj_type}")
                
                # If it's a callable, try to get more info
                if callable(obj):
                    try:
                        doc = obj.__doc__
                        if doc:
                            # Show first line of docstring
                            first_line = doc.split('\n')[0].strip()
                            if first_line:
                                print(f"       └─ {first_line}")
                    except:
                        pass
                        
            except Exception as attr_ex:
                print(f"   {i:2d}. {attr:<25} : Error - {attr_ex}")
        
        # Look for functions that might be entry points
        print(f"\n🔍 FUNCIONES DISPONIBLES:")
        functions = [attr for attr in public_attrs if callable(getattr(ts, attr, None))]
        
        for func_name in functions:
            try:
                func = getattr(ts, func_name)
                print(f"   📞 {func_name}")
                
                # Try to get function signature
                import inspect
                try:
                    sig = inspect.signature(func)
                    print(f"      Signature: {func_name}{sig}")
                except:
                    print(f"      Signature: No disponible")
                
                # Get docstring
                doc = func.__doc__
                if doc:
                    lines = doc.strip().split('\n')
                    for line in lines[:3]:  # Show first 3 lines
                        if line.strip():
                            print(f"      Doc: {line.strip()}")
                
            except Exception as func_ex:
                print(f"   📞 {func_name}: Error - {func_ex}")
        
        # Look for classes or types
        print(f"\n🏗️  CLASES/TIPOS DISPONIBLES:")
        types_found = []
        for attr in public_attrs:
            try:
                obj = getattr(ts, attr)
                obj_type = type(obj)
                
                # Check if it's a type/class
                if str(obj_type) in ['<class \'type\'>', '<class \'ABCMeta\'>'] or hasattr(obj, '__bases__'):
                    types_found.append(attr)
                    print(f"   🏷️  {attr}: {obj_type}")
                    
                    # Show methods of the class
                    methods = [m for m in dir(obj) if not m.startswith('_') and callable(getattr(obj, m, None))]
                    if methods:
                        print(f"      Methods: {', '.join(methods[:5])}")
                        if len(methods) > 5:
                            print(f"      ... and {len(methods)-5} more")
                            
            except Exception as type_ex:
                continue
        
        if not types_found:
            print("   ❌ No se encontraron clases obvias")
        
        # Try to find TIA Portal related functionality
        print(f"\n🎯 BÚSQUEDA DE FUNCIONALIDAD TIA PORTAL:")
        tia_keywords = ['tia', 'portal', 'open', 'connect', 'project', 'export']
        
        tia_related = []
        for attr in public_attrs:
            attr_lower = attr.lower()
            if any(keyword in attr_lower for keyword in tia_keywords):
                tia_related.append(attr)
        
        if tia_related:
            print("   Elementos relacionados con TIA Portal:")
            for attr in tia_related:
                try:
                    obj = getattr(ts, attr)
                    print(f"   ✅ {attr}: {type(obj).__name__}")
                except:
                    print(f"   ❌ {attr}: Error")
        else:
            print("   ❌ No se encontraron elementos obvios relacionados con TIA Portal")
        
        # Try some common function names that might exist
        print(f"\n🔍 PROBANDO FUNCIONES COMUNES:")
        common_functions = [
            'open_portal',
            'OpenPortal', 
            'open_project',
            'OpenProject',
            'connect',
            'Connect',
            'TiaPortal',
            'create_portal',
            'get_portal'
        ]
        
        for func_name in common_functions:
            if hasattr(ts, func_name):
                print(f"   ✅ {func_name}: Disponible")
                try:
                    func = getattr(ts, func_name)
                    print(f"      Tipo: {type(func).__name__}")
                    if callable(func):
                        try:
                            sig = inspect.signature(func)
                            print(f"      Signature: {func_name}{sig}")
                        except:
                            pass
                except:
                    pass
            else:
                print(f"   ❌ {func_name}: No disponible")
        
        # Check the module file for more info
        print(f"\n📁 INFORMACIÓN DEL ARCHIVO:")
        if hasattr(ts, '__file__'):
            print(f"   Archivo: {ts.__file__}")
            
            # Try to read some info from the file
            import os
            file_path = ts.__file__
            if os.path.exists(file_path):
                file_size = os.path.getsize(file_path)
                print(f"   Tamaño: {file_size:,} bytes")
                
                # Check if there are any associated files
                file_dir = os.path.dirname(file_path)
                files_in_dir = os.listdir(file_dir)
                related_files = [f for f in files_in_dir if 'siemens' in f.lower() or 'tia' in f.lower()]
                if related_files:
                    print(f"   Archivos relacionados:")
                    for f in related_files[:10]:
                        print(f"     - {f}")
        
        print(f"\n" + "="*70)
        print("🎯 ANÁLISIS COMPLETADO")
        print("="*70)
        
        return True
        
    except Exception as e:
        print(f"❌ Error durante la exploración: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == "__main__":
    success = explore_actual_api()
    
    if success:
        print(f"\n📋 Basándome en esta información, crearé el exportador correcto")
    else:
        print(f"\n❌ No se pudo explorar la API")
    
    input("\nPresiona Enter para salir...")