"""
Utilidades de serialización para convertir datos de BD a diccionarios.
"""


def tire_to_dict(tire):
    """Convert tire dict/row to dictionary."""
    if isinstance(tire, dict):
        # Ya es un diccionario
        return {
            'id': tire.get('id'),
            'brand': tire.get('marca') or tire.get('brand', ''),
            'model': tire.get('modelo') or tire.get('model', ''),
            'size': {
                'width': tire.get('ancho') or tire.get('width'),
                'aspectRatio': tire.get('relacion_aspecto') or tire.get('aspect_ratio'),
                'diameter': tire.get('diametro') or tire.get('diameter')
            },
            'type': tire.get('tipo') or tire.get('type', ''),
            'imageUrl': tire.get('url_imagen') or tire.get('image_url'),
            'created_at': tire.get('creado_en').isoformat() if tire.get('creado_en') else None
        }
    else:
        # Objeto con atributos
        return {
            'id': getattr(tire, 'id', ''),
            'brand': getattr(tire, 'marca', '') or getattr(tire, 'brand', ''),
            'model': getattr(tire, 'modelo', '') or getattr(tire, 'model', ''),
            'size': {
                'width': getattr(tire, 'ancho', None) or getattr(tire, 'width', None),
                'aspectRatio': getattr(tire, 'relacion_aspecto', None) or getattr(tire, 'aspect_ratio', None),
                'diameter': getattr(tire, 'diametro', None) or getattr(tire, 'diameter', None)
            },
            'type': getattr(tire, 'tipo', '') or getattr(tire, 'type', ''),
            'imageUrl': getattr(tire, 'url_imagen', None) or getattr(tire, 'image_url', None),
            'created_at': getattr(tire, 'creado_en', None).isoformat() if getattr(tire, 'creado_en', None) else None
        }


def business_to_dict(business):
    """Convert business dict/row to dictionary."""
    if not business:
        return None
    
    if isinstance(business, dict):
        email = business.get('correo') or business.get('email', '')
        return {
            'id': business.get('id', ''),
            'name': business.get('nombre') or business.get('name', ''),
            'address': business.get('direccion') or business.get('address', ''),
            'contact': {
                'phone': business.get('telefono') or business.get('phone', ''),
                'email': email
            },
            'hours': business.get('horarios') or business.get('hours', ''),
            'rating': float(business.get('calificacion') or business.get('rating') or 0.0),
            'reviewCount': int(business.get('cantidad_resenas') or business.get('review_count') or 0),
            'description': business.get('descripcion') or business.get('description'),
            'googleMapsEmbedUrl': business.get('url_mapa_google') or business.get('google_maps_embed_url'),
            'imageUrl': business.get('url_imagen') or business.get('image_url'),
            'socials': business.get('redes_sociales') or business.get('socials'),
            'created_at': business.get('creado_en').isoformat() if business.get('creado_en') else None
        }
    else:
        email = getattr(business, 'correo', None) or getattr(business, 'email', '')
        return {
            'id': getattr(business, 'id', ''),
            'name': getattr(business, 'nombre', '') or getattr(business, 'name', ''),
            'address': getattr(business, 'direccion', '') or getattr(business, 'address', ''),
            'contact': {
                'phone': getattr(business, 'telefono', '') or getattr(business, 'phone', ''),
                'email': email
            },
            'hours': getattr(business, 'horarios', '') or getattr(business, 'hours', ''),
            'rating': float(getattr(business, 'calificacion', 0) or getattr(business, 'rating', 0)),
            'reviewCount': int(getattr(business, 'cantidad_resenas', 0) or getattr(business, 'review_count', 0)),
            'description': getattr(business, 'descripcion', None) or getattr(business, 'description', None),
            'googleMapsEmbedUrl': getattr(business, 'url_mapa_google', None) or getattr(business, 'google_maps_embed_url', None),
            'imageUrl': getattr(business, 'url_imagen', None) or getattr(business, 'image_url', None),
            'socials': getattr(business, 'redes_sociales', None) or getattr(business, 'socials', None),
            'created_at': getattr(business, 'creado_en', None).isoformat() if getattr(business, 'creado_en', None) else None
        }


def user_to_dict(user, include_sensitive=False):
    """Convert user dict/row to dictionary."""
    if isinstance(user, dict):
        result = {
            'id': user.get('id'),
            'username': user.get('nombre_usuario') or user.get('username', ''),
            'full_name': user.get('nombre_completo') or user.get('full_name', ''),
            'email': user.get('correo') or user.get('email', ''),
            'phone': user.get('celular') or user.get('phone', ''),
            'role': user.get('rol') or user.get('role', ''),  # BD: rol, código: role
            'business_id': user.get('negocio_id') or user.get('business_id'),  # BD: negocio_id, código: business_id
            'business_application_status': user.get('estado_solicitud_negocio') or user.get('business_application_status'),  # BD: estado_solicitud_negocio
            'created_at': user.get('creado_en').isoformat() if user.get('creado_en') else None
        }
        if include_sensitive:
            result['hash_contraseña'] = user.get('hash_contraseña') or user.get('hash_password')
        return result
    else:
        result = {
            'id': getattr(user, 'id', ''),
            'username': getattr(user, 'nombre_usuario', '') or getattr(user, 'username', ''),
            'full_name': getattr(user, 'nombre_completo', '') or getattr(user, 'full_name', ''),
            'email': getattr(user, 'correo', '') or getattr(user, 'email', ''),
            'phone': getattr(user, 'celular', '') or getattr(user, 'phone', ''),
            'role': getattr(user, 'rol', '') or getattr(user, 'role', ''),
            'business_id': getattr(user, 'negocio_id', None) or getattr(user, 'business_id', None),
            'business_application_status': getattr(user, 'estado_solicitud_negocio', None) or getattr(user, 'business_application_status', None),
            'created_at': getattr(user, 'creado_en', None).isoformat() if getattr(user, 'creado_en', None) else None
        }
        if include_sensitive:
            result['hash_contraseña'] = getattr(user, 'hash_contraseña', None) or getattr(user, 'hash_password', None)
        return result


def inventory_to_dict(item):
    """Convert inventory dict/row to dictionary."""
    if isinstance(item, dict):
        return {
            'id': item.get('id'),
            'business_id': item.get('negocio_id') or item.get('business_id'),
            'tire_id': item.get('llanta_id') or item.get('tire_id'),
            'quantity': item.get('cantidad') or item.get('quantity', 0),
            'price': float(item.get('precio') or item.get('price', 0)),
            'created_at': item.get('creado_en').isoformat() if item.get('creado_en') else None
        }
    else:
        return {
            'id': getattr(item, 'id', ''),
            'business_id': getattr(item, 'negocio_id', None) or getattr(item, 'business_id', None),
            'tire_id': getattr(item, 'llanta_id', None) or getattr(item, 'tire_id', None),
            'quantity': getattr(item, 'cantidad', 0) or getattr(item, 'quantity', 0),
            'price': float(getattr(item, 'precio', 0) or getattr(item, 'price', 0)),
            'created_at': getattr(item, 'creado_en', None).isoformat() if getattr(item, 'creado_en', None) else None
        }


def review_to_dict(review):
    """Convert review dict/row to dictionary."""
    if isinstance(review, dict):
        return {
            'id': review.get('id'),
            'business_id': review.get('negocio_id') or review.get('business_id'),
            'user_id': review.get('usuario_id') or review.get('user_id'),
            'user_name': review.get('nombre_usuario') or review.get('user_name', ''),
            'user_avatar': review.get('avatar_usuario') or review.get('user_avatar'),
            'rating': int(review.get('calificacion') or review.get('rating', 0)),
            'comment': review.get('comentario') or review.get('comment', ''),
            'created_at': review.get('creado_en').isoformat() if review.get('creado_en') else None
        }
    else:
        return {
            'id': getattr(review, 'id', ''),
            'business_id': getattr(review, 'negocio_id', None) or getattr(review, 'business_id', None),
            'user_id': getattr(review, 'usuario_id', None) or getattr(review, 'user_id', None),
            'user_name': getattr(review, 'nombre_usuario', '') or getattr(review, 'user_name', ''),
            'user_avatar': getattr(review, 'avatar_usuario', None) or getattr(review, 'user_avatar', None),
            'rating': int(getattr(review, 'calificacion', 0) or getattr(review, 'rating', 0)),
            'comment': getattr(review, 'comentario', '') or getattr(review, 'comment', ''),
            'created_at': getattr(review, 'creado_en', None).isoformat() if getattr(review, 'creado_en', None) else None
        }


def favorite_to_dict(favorite):
    """Convert favorite dict/row to dictionary."""
    if isinstance(favorite, dict):
        return {
            'id': favorite.get('id'),
            'user_id': favorite.get('usuario_id') or favorite.get('user_id'),
            'tire_id': favorite.get('llanta_id') or favorite.get('tire_id'),
            'created_at': favorite.get('creado_en').isoformat() if favorite.get('creado_en') else None
        }
    else:
        return {
            'id': getattr(favorite, 'id', ''),
            'user_id': getattr(favorite, 'usuario_id', None) or getattr(favorite, 'user_id', None),
            'tire_id': getattr(favorite, 'llanta_id', None) or getattr(favorite, 'tire_id', None),
            'created_at': getattr(favorite, 'creado_en', None).isoformat() if getattr(favorite, 'creado_en', None) else None
        }


def search_history_to_dict(history_item):
    """Convert search history dict/row to dictionary."""
    import json
    if isinstance(history_item, dict):
        filtros = history_item.get('filtros')
        if isinstance(filtros, str):
            try:
                filtros = json.loads(filtros)
            except:
                filtros = None
        
        return {
            'id': history_item.get('id'),
            'user_id': history_item.get('usuario_id') or history_item.get('user_id'),
            'type': history_item.get('tipo') or history_item.get('type'),
            'search_term': history_item.get('termino_busqueda') or history_item.get('search_term'),
            'filters': filtros or history_item.get('filters'),
            'entity_id': history_item.get('entidad_id') or history_item.get('entity_id'),
            'created_at': history_item.get('creado_en').isoformat() if history_item.get('creado_en') else None
        }
    else:
        filtros = getattr(history_item, 'filtros', None)
        if isinstance(filtros, str):
            try:
                filtros = json.loads(filtros)
            except:
                filtros = None
        
        return {
            'id': getattr(history_item, 'id', ''),
            'user_id': getattr(history_item, 'usuario_id', None) or getattr(history_item, 'user_id', None),
            'type': getattr(history_item, 'tipo', None) or getattr(history_item, 'type', None),
            'search_term': getattr(history_item, 'termino_busqueda', None) or getattr(history_item, 'search_term', None),
            'filters': filtros or getattr(history_item, 'filters', None),
            'entity_id': getattr(history_item, 'entidad_id', None) or getattr(history_item, 'entity_id', None),
            'created_at': getattr(history_item, 'creado_en', None).isoformat() if getattr(history_item, 'creado_en', None) else None
        }


def price_alert_to_dict(alert):
    """Convert price alert dict/row to dictionary."""
    if isinstance(alert, dict):
        return {
            'id': alert.get('id'),
            'user_id': alert.get('usuario_id') or alert.get('user_id'),
            'tire_id': alert.get('llanta_id') or alert.get('tire_id'),
            'business_id': alert.get('negocio_id') or alert.get('business_id'),
            'max_price': float(alert.get('precio_maximo') or alert.get('max_price', 0)) if alert.get('precio_maximo') or alert.get('max_price') else None,
            'active': bool(alert.get('activo') if alert.get('activo') is not None else alert.get('active', True)),
            'notified': bool(alert.get('notificado') if alert.get('notificado') is not None else alert.get('notified', False)),
            'created_at': alert.get('creado_en').isoformat() if alert.get('creado_en') else None,
            'updated_at': alert.get('actualizado_en').isoformat() if alert.get('actualizado_en') else None
        }
    else:
        return {
            'id': getattr(alert, 'id', ''),
            'user_id': getattr(alert, 'usuario_id', None) or getattr(alert, 'user_id', None),
            'tire_id': getattr(alert, 'llanta_id', None) or getattr(alert, 'tire_id', None),
            'business_id': getattr(alert, 'negocio_id', None) or getattr(alert, 'business_id', None),
            'max_price': float(getattr(alert, 'precio_maximo', 0) or getattr(alert, 'max_price', 0)) if getattr(alert, 'precio_maximo', None) or getattr(alert, 'max_price', None) else None,
            'active': bool(getattr(alert, 'activo', True) if getattr(alert, 'activo', None) is not None else getattr(alert, 'active', True)),
            'notified': bool(getattr(alert, 'notificado', False) if getattr(alert, 'notificado', None) is not None else getattr(alert, 'notified', False)),
            'created_at': getattr(alert, 'creado_en', None).isoformat() if getattr(alert, 'creado_en', None) else None,
            'updated_at': getattr(alert, 'actualizado_en', None).isoformat() if getattr(alert, 'actualizado_en', None) else None
        }


def saved_comparison_to_dict(comparison):
    """Convert saved comparison dict/row to dictionary."""
    import json
    if isinstance(comparison, dict):
        llantas_ids = comparison.get('llantas_ids')
        if isinstance(llantas_ids, str):
            try:
                llantas_ids = json.loads(llantas_ids)
            except:
                llantas_ids = []
        elif not isinstance(llantas_ids, list):
            llantas_ids = []
        
        return {
            'id': comparison.get('id'),
            'user_id': comparison.get('usuario_id') or comparison.get('user_id'),
            'name': comparison.get('nombre') or comparison.get('name'),
            'tire_ids': llantas_ids or comparison.get('tire_ids', []),
            'notes': comparison.get('notas') or comparison.get('notes'),
            'share_token': comparison.get('compartir_token') or comparison.get('share_token'),
            'created_at': comparison.get('creado_en').isoformat() if comparison.get('creado_en') else None,
            'updated_at': comparison.get('actualizado_en').isoformat() if comparison.get('actualizado_en') else None
        }
    else:
        llantas_ids = getattr(comparison, 'llantas_ids', None)
        if isinstance(llantas_ids, str):
            try:
                llantas_ids = json.loads(llantas_ids)
            except:
                llantas_ids = []
        elif not isinstance(llantas_ids, list):
            llantas_ids = []
        
        return {
            'id': getattr(comparison, 'id', ''),
            'user_id': getattr(comparison, 'usuario_id', None) or getattr(comparison, 'user_id', None),
            'name': getattr(comparison, 'nombre', None) or getattr(comparison, 'name', None),
            'tire_ids': llantas_ids or getattr(comparison, 'tire_ids', []),
            'notes': getattr(comparison, 'notas', None) or getattr(comparison, 'notes', None),
            'share_token': getattr(comparison, 'compartir_token', None) or getattr(comparison, 'share_token', None),
            'created_at': getattr(comparison, 'creado_en', None).isoformat() if getattr(comparison, 'creado_en', None) else None,
            'updated_at': getattr(comparison, 'actualizado_en', None).isoformat() if getattr(comparison, 'actualizado_en', None) else None
        }
