"""
Router para manejo de historial de búsquedas y actividad del usuario.
"""
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required
from app.db import get_db_connection
from app.auth import get_current_user
from app.utils.validators import validate_pagination_params
from app.utils.serializers import search_history_to_dict
from app.utils.logger import get_logger
from datetime import datetime, timezone
import uuid
import json

history_bp = Blueprint('history', __name__)
logger = get_logger(__name__)


@history_bp.route('', methods=['GET'])
@jwt_required()
def get_history():
    """Get search and activity history for the current user."""
    user = get_current_user()
    if not user:
        return jsonify({'error': 'Authentication required'}), 401
    
    skip = request.args.get('skip', 0, type=int)
    limit = request.args.get('limit', 50, type=int)
    history_type = request.args.get('type')  # Optional filter by type
    
    # Validar paginación
    valid, skip_val, limit_val, error_msg = validate_pagination_params(skip, limit, max_limit=100)
    if not valid:
        return jsonify({'error': error_msg}), 400
    
    conn = get_db_connection()
    if not conn:
        return jsonify({'error': 'Database connection error'}), 500
    
    try:
        cursor = conn.cursor()
        user_id = user.get('id')
        
        # Construir query con filtro opcional por tipo
        if history_type:
            cursor.execute("""
                SELECT id, usuario_id, tipo, termino_busqueda, filtros, entidad_id, creado_en
                FROM historial_busquedas
                WHERE usuario_id = %s AND tipo = %s
                ORDER BY creado_en DESC
                LIMIT %s OFFSET %s
            """, (user_id, history_type, limit_val, skip_val))
            
            cursor.execute("""
                SELECT COUNT(*) as total
                FROM historial_busquedas
                WHERE usuario_id = %s AND tipo = %s
            """, (user_id, history_type))
        else:
            cursor.execute("""
                SELECT id, usuario_id, tipo, termino_busqueda, filtros, entidad_id, creado_en
                FROM historial_busquedas
                WHERE usuario_id = %s
                ORDER BY creado_en DESC
                LIMIT %s OFFSET %s
            """, (user_id, limit_val, skip_val))
            
            cursor.execute("""
                SELECT COUNT(*) as total
                FROM historial_busquedas
                WHERE usuario_id = %s
            """, (user_id,))
        
        history_data = cursor.fetchall()
        total_result = cursor.fetchone()
        total_count = total_result['total'] if total_result else 0
        
        cursor.close()
        conn.close()
        
        return jsonify({
            'history': [search_history_to_dict(item) for item in history_data],
            'pagination': {
                'skip': skip_val,
                'limit': limit_val,
                'total': total_count,
                'has_more': (skip_val + limit_val) < total_count
            }
        }), 200
    
    except Exception as e:
        if 'cursor' in locals():
            cursor.close()
        if conn:
            conn.close()
        logger.error(f"Error in get_history: {str(e)}", exc_info=True, extra={
            'endpoint': 'get_history',
            'user_id': user.get('id') if user else None
        })
        return jsonify({'error': 'Error retrieving history'}), 500


@history_bp.route('', methods=['POST'])
@jwt_required()
def log_activity():
    """Log a search or activity to user's history."""
    user = get_current_user()
    if not user:
        return jsonify({'error': 'Authentication required'}), 401
    
    data = request.get_json()
    if not data:
        return jsonify({'error': 'Request body is required'}), 400
    
    activity_type = data.get('type')
    search_term = data.get('search_term')
    filters = data.get('filters')
    entity_id = data.get('entity_id')
    
    if not activity_type:
        return jsonify({'error': 'type is required'}), 400
    
    # Validar tipos permitidos
    valid_types = ['tire_search', 'business_search', 'tire_view', 'business_view']
    if activity_type not in valid_types:
        return jsonify({'error': f'type must be one of: {", ".join(valid_types)}'}), 400
    
    conn = get_db_connection()
    if not conn:
        return jsonify({'error': 'Database connection error'}), 500
    
    try:
        cursor = conn.cursor()
        user_id = user.get('id')
        
        # Convertir filtros a JSON string si es un dict
        filters_json = None
        if filters:
            if isinstance(filters, dict):
                filters_json = json.dumps(filters)
            elif isinstance(filters, str):
                filters_json = filters
        
        # Crear entrada de historial
        history_id = f"hist-{user_id}-{uuid.uuid4().hex[:12]}"
        cursor.execute("""
            INSERT INTO historial_busquedas (id, usuario_id, tipo, termino_busqueda, filtros, entidad_id, creado_en)
            VALUES (%s, %s, %s, %s, %s, %s, %s)
        """, (history_id, user_id, activity_type, search_term, filters_json, entity_id, datetime.now(timezone.utc)))
        
        conn.commit()
        
        # Log change for audit
        from app.governance.audit import log_change
        log_change(
            table='historial_busquedas',
            record_id=history_id,
            action='INSERT',
            user_id=user_id,
            user_email=user.get('correo'),
            new_data={
                'tipo': activity_type,
                'termino_busqueda': search_term,
                'entidad_id': entity_id
            }
        )
        
        # Obtener entrada creada
        cursor.execute("""
            SELECT id, usuario_id, tipo, termino_busqueda, filtros, entidad_id, creado_en
            FROM historial_busquedas WHERE id = %s
        """, (history_id,))
        history_data = cursor.fetchone()
        
        cursor.close()
        conn.close()
        
        return jsonify(search_history_to_dict(history_data)), 201
    
    except Exception as e:
        if conn:
            conn.rollback()
            if 'cursor' in locals():
                cursor.close()
            conn.close()
        logger.error(f"Error in log_activity: {str(e)}", exc_info=True, extra={
            'endpoint': 'log_activity',
            'user_id': user.get('id') if user else None,
            'activity_type': activity_type
        })
        return jsonify({'error': 'Error logging activity'}), 500


@history_bp.route('/<history_id>', methods=['DELETE'])
@jwt_required()
def delete_history_item(history_id):
    """Delete a specific history item."""
    user = get_current_user()
    if not user:
        return jsonify({'error': 'Authentication required'}), 401
    
    conn = get_db_connection()
    if not conn:
        return jsonify({'error': 'Database connection error'}), 500
    
    try:
        cursor = conn.cursor()
        user_id = user.get('id')
        
        # Verificar que el historial pertenece al usuario
        cursor.execute("""
            SELECT id FROM historial_busquedas
            WHERE id = %s AND usuario_id = %s
        """, (history_id, user_id))
        
        if not cursor.fetchone():
            cursor.close()
            conn.close()
            return jsonify({'error': 'History item not found'}), 404
        
        # Eliminar
        cursor.execute("DELETE FROM historial_busquedas WHERE id = %s", (history_id,))
        conn.commit()
        
        cursor.close()
        conn.close()
        
        return '', 204
    
    except Exception as e:
        if conn:
            conn.rollback()
            if 'cursor' in locals():
                cursor.close()
            conn.close()
        logger.error(f"Error in delete_history_item: {str(e)}", exc_info=True, extra={
            'endpoint': 'delete_history_item',
            'user_id': user.get('id') if user else None,
            'history_id': history_id
        })
        return jsonify({'error': 'Error deleting history item'}), 500


@history_bp.route('/clear', methods=['DELETE'])
@jwt_required()
def clear_history():
    """Clear all history for the current user."""
    user = get_current_user()
    if not user:
        return jsonify({'error': 'Authentication required'}), 401
    
    data = request.get_json() or {}
    history_type = data.get('type')  # Opcional: limpiar solo un tipo específico
    
    conn = get_db_connection()
    if not conn:
        return jsonify({'error': 'Database connection error'}), 500
    
    try:
        cursor = conn.cursor()
        user_id = user.get('id')
        
        if history_type:
            # Eliminar solo el tipo especificado
            cursor.execute("""
                DELETE FROM historial_busquedas
                WHERE usuario_id = %s AND tipo = %s
            """, (user_id, history_type))
        else:
            # Eliminar todo el historial
            cursor.execute("""
                DELETE FROM historial_busquedas
                WHERE usuario_id = %s
            """, (user_id,))
        
        deleted_count = cursor.rowcount
        conn.commit()
        
        cursor.close()
        conn.close()
        
        return jsonify({
            'message': 'History cleared successfully',
            'deleted_count': deleted_count
        }), 200
    
    except Exception as e:
        if conn:
            conn.rollback()
            if 'cursor' in locals():
                cursor.close()
            conn.close()
        logger.error(f"Error in clear_history: {str(e)}", exc_info=True, extra={
            'endpoint': 'clear_history',
            'user_id': user.get('id') if user else None,
            'history_type': history_type
        })
        return jsonify({'error': 'Error clearing history'}), 500


@history_bp.route('/recent', methods=['GET'])
@jwt_required()
def get_recent_activity():
    """Get recent activity (last 10 items) for quick access."""
    user = get_current_user()
    if not user:
        return jsonify({'error': 'Authentication required'}), 401
    
    conn = get_db_connection()
    if not conn:
        return jsonify({'error': 'Database connection error'}), 500
    
    try:
        cursor = conn.cursor()
        user_id = user.get('id')
        
        cursor.execute("""
            SELECT id, usuario_id, tipo, termino_busqueda, filtros, entidad_id, creado_en
            FROM historial_busquedas
            WHERE usuario_id = %s
            ORDER BY creado_en DESC
            LIMIT 10
        """, (user_id,))
        
        history_data = cursor.fetchall()
        
        cursor.close()
        conn.close()
        
        return jsonify({
            'recent': [search_history_to_dict(item) for item in history_data]
        }), 200
    
    except Exception as e:
        if 'cursor' in locals():
            cursor.close()
        if conn:
            conn.close()
        logger.error(f"Error in get_recent_activity: {str(e)}", exc_info=True, extra={
            'endpoint': 'get_recent_activity',
            'user_id': user.get('id') if user else None
        })
        return jsonify({'error': 'Error retrieving recent activity'}), 500
