"""
Doubts and Q&A system routes
"""
import json
import logging
import traceback
from flask import Blueprint, request, jsonify
from utils import require_api_key, encrypt_response, format_api_response, create_error_response


logger = logging.getLogger(__name__)
doubts_bp = Blueprint('doubts', __name__)


@doubts_bp.route('/doubts', methods=['GET'])
@require_api_key
# @encrypt_response
def get_all_doubts_route():
    user_id = request.values.get('user_id')
    # Handle 'null' or 'undefined' strings that might come from frontend
    if user_id in ('null', 'undefined', ''):
        user_id = None
        
    try:
        # Convert limit and offset to integers with proper error handling
        try:
            limit = int(request.args.get('limit', 20))
            offset = int(request.args.get('offset', 0))
        except (ValueError, TypeError) as e:
            logger.warning(f"Invalid limit/offset parameters: {e}. Using defaults.")
            limit = 20
            offset = 0
        
        # Process filters with proper type handling
        filters = {}
        
        # Course ID - try to convert to integer
        course_id = request.args.get('course_id')
        if course_id:
            try:
                filters['course_id'] = int(course_id)
            except (ValueError, TypeError):
                logger.warning(f"Invalid course_id format: {course_id}. Skipping filter.")
        
        # Is solved - convert string to boolean
        is_solved = request.args.get('is_solved')
        if is_solved is not None:
            filters['is_solved'] = is_solved.lower() == 'true'
        
        # Other filters that don't need type conversion
        if request.args.get('search'):
            filters['search_query'] = request.args.get('search')
            
        if request.args.get('tag'):
            filters['tag'] = request.args.get('tag')
            
        if request.args.get('sort_by'):
            filters['sort_by'] = request.args.get('sort_by', 'recent')
        
        logger.debug(f"get_all_doubts_route called with user_id={user_id}, limit={limit}, offset={offset}, filters={filters}")
        
        # Import the function here to avoid circular imports
        from doubts import get_all_doubts
        result = get_all_doubts(user_id=user_id, limit=limit, offset=offset, filters=filters)
        
        # If result is a dictionary with 'success' key, return it directly
        if isinstance(result, dict) and 'success' in result:
            return format_api_response(result, include_legacy_fields=result)
            
        # Otherwise, wrap it in a success response
        return format_api_response(result, include_legacy_fields={'success': True, **result})
    except ValueError as e:
        # Handle conversion errors for limit/offset
        logger.error(f"Invalid parameter format: {str(e)}", exc_info=True)
        return create_error_response(f'Invalid parameter format: {str(e)}', 400)
    except Exception as e:
        # Generic error handler
        logger.error(f"Server error in get_all_doubts_route: {str(e)}", exc_info=True)
        return create_error_response(f'Server error: {str(e)}', 500)


@doubts_bp.route('/doubts', methods=['POST'])
@require_api_key
# @encrypt_response
def create_doubt_route():
    user_id = request.values.get('user_id')
    # Handle 'null' or 'undefined' strings that might come from frontend
    if user_id in ('null', 'undefined', ''):
        user_id = None
        
    try:
        # Log the raw request data for debugging
        logger.debug(f"Received doubt creation request: user_id={user_id}")
        logger.debug(f"Request JSON data: {request.get_json(silent=True)}")
        logger.debug(f"Request form data: {request.form}")
        
        # Get data from JSON or form data
        data = request.get_json(silent=True) or {}
        
        title = data.get('title') or request.form.get('title')
        content = data.get('content') or request.form.get('content')
        
        # Handle tags - could be a list, a string, or a JSON string
        tags_data = data.get('tags') or request.form.getlist('tags[]') or request.form.get('tags') or []
        tags = []
        
        if isinstance(tags_data, str):
            try:
                # Try to parse as JSON
                import json
                parsed_tags = json.loads(tags_data)
                if isinstance(parsed_tags, list):
                    tags = parsed_tags
                else:
                    # If not a list, split by comma
                    tags = [tag.strip() for tag in tags_data.split(',') if tag.strip()]
            except json.JSONDecodeError:
                # If not valid JSON, split by comma
                tags = [tag.strip() for tag in tags_data.split(',') if tag.strip()]
        else:
            tags = tags_data
            
        # Process IDs - check for placeholder values
        course_id = data.get('course_id') or request.form.get('course_id')
        if course_id in ('course_id', 'null', 'undefined', ''):
            course_id = None
            
        topic_id = data.get('topic_id') or request.form.get('topic_id')
        if topic_id in ('topic_id', 'null', 'undefined', ''):
            topic_id = None
            
        video_id = data.get('video_id') or request.form.get('video_id')
        if video_id in ('video_id', 'null', 'undefined', ''):
            video_id = None
        
        logger.debug(f"Processed request data: title='{title}', content_length={len(content) if content else 0}, tags={tags}, course_id={course_id}")
        
        if not user_id:
            logger.warning("Doubt creation failed: No user_id provided")
            return create_error_response('User ID required', 401)
            
        if not title or not content:
            logger.warning("Doubt creation failed: Missing title or content")
            return create_error_response('Title and content are required', 400)
        
        # Import the function here to avoid circular imports
        from doubts import create_doubt
        result = create_doubt(title=title, content=content, user_id=user_id, 
                          tags=tags, course_id=course_id, topic_id=topic_id, video_id=video_id)
                          
        # If result is a dictionary with 'success' key, return it directly
        if isinstance(result, dict) and 'success' in result:
            return format_api_response(result, include_legacy_fields=result)
            
        # Otherwise, wrap it in a success response (for backward compatibility)
        success_response = {
            'success': True,
            'doubt': result,
            'message': 'Doubt created successfully'
        }
        return format_api_response(result, include_legacy_fields=success_response)
    except ValueError as e:
        # Handle validation errors
        logger.error(f"Validation error in create_doubt_route: {str(e)}")
        return create_error_response(str(e), 400)
    except Exception as e:
        logger.error(f"Error in create_doubt_route: {str(e)}", exc_info=True)
        return create_error_response(f'Server error: {str(e)}', 500)


@doubts_bp.route('/doubts/<int:doubt_id>', methods=['GET'])
@require_api_key
# @encrypt_response
def get_doubt_by_id_route(doubt_id):
    user_id = request.values.get('user_id')
    # Handle 'null' or 'undefined' strings that might come from frontend
    if user_id in ('null', 'undefined', ''):
        user_id = None
    
    logger.debug(f"get_doubt_by_id_route called with doubt_id={doubt_id}, user_id={user_id}")
    
    try:
        # Import the function here to avoid circular imports
        from doubts import get_doubt_by_id
        result = get_doubt_by_id(doubt_id=doubt_id, user_id=user_id)
        
        if result is None:
            logger.warning(f"Doubt not found with id={doubt_id}")
            return create_error_response('Doubt not found', 404)
        
        # If result is a dictionary with 'success' key, return it directly
        if isinstance(result, dict) and 'success' in result:
            return format_api_response(result, include_legacy_fields=result)
            
        # Otherwise, wrap it in a success response (for backward compatibility)
        return format_api_response(result, include_legacy_fields={'success': True, 'doubt': result})
    except Exception as e:
        logger.error(f"Failed to fetch doubt details: {str(e)}")
        logger.error(f"Stack trace: {traceback.format_exc()}")
        return create_error_response(f"Error fetching doubt: {str(e)}", 500)


@doubts_bp.route('/doubts/<int:doubt_id>/answers', methods=['POST'])
@require_api_key
@encrypt_response
def create_answer_route(doubt_id):
    user_id = request.values.get('user_id')
    data = request.get_json(silent=True) or {}
    
    content = data.get('content') or request.form.get('content')
    is_by_mentor = data.get('is_by_mentor') or request.form.get('is_by_mentor') == '1'
    
    if not user_id:
        return {'error': 'Unauthorized', 'message': 'User ID required'}, 401
    if not content:
        return {'error': 'Bad request', 'message': 'Content is required'}, 400
    
    # Import the function here to avoid circular imports    
    from doubts import create_answer
    result = create_answer(doubt_id=doubt_id, content=content, user_id=user_id, is_by_mentor=is_by_mentor)
    return result, 201


@doubts_bp.route('/doubts/<int:doubt_id>/like', methods=['POST'])
@require_api_key
@encrypt_response
def like_doubt_route(doubt_id):
    user_id = request.values.get('user_id')
    if not user_id:
        return {'error': 'Unauthorized', 'message': 'User ID required'}, 401
    
    # Import the function here to avoid circular imports    
    from doubts import toggle_like_doubt
    result = toggle_like_doubt(doubt_id=doubt_id, user_id=user_id)
    return result


@doubts_bp.route('/doubts/<int:doubt_id>/bookmark', methods=['POST'])
@require_api_key
@encrypt_response
def bookmark_doubt_route(doubt_id):
    user_id = request.values.get('user_id')
    if not user_id:
        return {'error': 'Unauthorized', 'message': 'User ID required'}, 401
    
    # Import the function here to avoid circular imports    
    from doubts import toggle_bookmark_doubt
    result = toggle_bookmark_doubt(doubt_id=doubt_id, user_id=user_id)
    return result


@doubts_bp.route('/answers/<int:answer_id>/like', methods=['POST'])
@require_api_key
@encrypt_response
def like_answer_route(answer_id):
    user_id = request.values.get('user_id')
    if not user_id:
        return {'error': 'Unauthorized', 'message': 'User ID required'}, 401
    
    # Import the function here to avoid circular imports    
    from doubts import toggle_like_answer
    result = toggle_like_answer(answer_id=answer_id, user_id=user_id)
    return result


@doubts_bp.route('/answers/<int:answer_id>/accept', methods=['POST'])
@require_api_key
@encrypt_response
def accept_answer_route(answer_id):
    user_id = request.values.get('user_id')
    data = request.get_json(silent=True) or {}
    doubt_id = data.get('doubt_id') or request.form.get('doubt_id')
    
    if not user_id:
        return {'error': 'Unauthorized', 'message': 'User ID required'}, 401
    if not doubt_id:
        return {'error': 'Bad request', 'message': 'Doubt ID is required'}, 400
    
    # Import the function here to avoid circular imports    
    from doubts import accept_answer
    result = accept_answer(answer_id=answer_id, doubt_id=doubt_id, user_id=user_id)
    return result if not isinstance(result, tuple) else result


@doubts_bp.route('/tags/popular', methods=['GET'])
@require_api_key
@encrypt_response
def popular_tags_route():
    limit = int(request.args.get('limit', 10))
    
    # Import the function here to avoid circular imports    
    from doubts import get_popular_tags
    result = get_popular_tags(limit=limit)
    return {'tags': result}


@doubts_bp.route('/user/bookmarks', methods=['GET'])
@require_api_key
@encrypt_response
def user_bookmarks_route():
    user_id = request.values.get('user_id')
    if not user_id:
        return {'error': 'Unauthorized', 'message': 'User ID required'}, 401
    
    limit = int(request.args.get('limit', 20))
    offset = int(request.args.get('offset', 0))
    
    # Import the function here to avoid circular imports    
    from doubts import get_user_bookmarked_doubts
    result = get_user_bookmarked_doubts(user_id=user_id, limit=limit, offset=offset)
    return result