"""
SuperApp Tools Routes
Handles ONLY the missing SuperApp functionality that needs backend APIs:
- Academic Tools (GPA calculator, study timer, assignment tracker, grade tracker)  
- Financial Tools (EMI calculator, budget planner, investment guide, savings tracker)
- Study Aids (dictionary, translator, unit converter)
- Productivity (task manager)

NOTE: Scholarships, Colleges, Schools, and News are already working via reverse proxy routes
"""
from flask import Blueprint, request, jsonify, make_response
from utils import require_api_key, add_keep_alive, format_api_response, create_error_response
from auth.jwt_manager import require_auth, require_user_access
from database import get_cached_connection, optimized_execute
import logging
import json
import re
from datetime import datetime, timedelta
import math

logger = logging.getLogger(__name__)

superapp_bp = Blueprint('superapp', __name__)

# ============================================================================
# ACADEMIC TOOLS SECTION
# ============================================================================

@superapp_bp.route('/api/superapp/academic-tools/gpa-calculator', methods=['POST'])
@require_api_key
def calculate_gpa():
    """Calculate GPA from grades"""
    try:
        data = request.get_json()
        grades = data.get('grades', [])
        
        if not grades:
            return create_error_response("Grades are required", 400)
        
        # GPA scale mapping
        grade_points = {
            'A+': 4.0, 'A': 4.0, 'A-': 3.7,
            'B+': 3.3, 'B': 3.0, 'B-': 2.7,
            'C+': 2.3, 'C': 2.0, 'C-': 1.7,
            'D+': 1.3, 'D': 1.0, 'F': 0.0
        }
        
        total_points = 0
        total_credits = 0
        
        for grade_info in grades:
            grade = grade_info.get('grade', '').upper()
            credits = grade_info.get('credits', 1)
            
            if grade in grade_points:
                total_points += grade_points[grade] * credits
                total_credits += credits
        
        gpa = total_points / total_credits if total_credits > 0 else 0
        
        gpa_data = {
            'gpa': round(gpa, 2),
            'total_credits': total_credits,
            'grade_breakdown': grades,
            'total_points': total_points
        }
        return format_api_response(gpa_data, include_legacy_fields=gpa_data)
        
    except Exception as e:
        logger.error(f"Error calculating GPA: {str(e)}")
        return create_error_response("Failed to calculate GPA", 500)

@superapp_bp.route('/api/superapp/academic-tools/study-timer', methods=['POST'])
@require_api_key
@require_auth
def create_study_session():
    """Create a study timer session"""
    try:
        user_id = request.current_user['user_id']
        data = request.get_json()
        
        duration_minutes = data.get('duration_minutes', 25)
        subject = data.get('subject', 'General Study')
        break_duration = data.get('break_duration', 5)
        
        with get_cached_connection() as conn:
            cursor = conn.cursor()
            
            query = """
            INSERT INTO study_sessions (user_id, subject, duration_minutes, break_duration, status, created_at)
            VALUES (%s, %s, %s, %s, 'active', %s)
            """
            
            cursor.execute(query, (user_id, subject, duration_minutes, break_duration, datetime.now()))
            session_id = cursor.lastrowid
            conn.commit()
            
            session_data = {
                'session_id': session_id,
                'duration_minutes': duration_minutes,
                'subject': subject,
                'break_duration': break_duration,
                'start_time': datetime.now().isoformat(),
                'status': 'active'
            }
            return format_api_response(session_data, include_legacy_fields=session_data)
            
    except Exception as e:
        logger.error(f"Error creating study session: {str(e)}")
        return create_error_response("Failed to create study session", 500)

@superapp_bp.route('/api/superapp/academic-tools/study-timer/<int:session_id>', methods=['PUT'])
@require_api_key
@require_auth
def update_study_session(session_id):
    """Update study timer session (complete, pause, etc.)"""
    try:
        user_id = request.current_user['user_id']
        data = request.get_json()
        
        status = data.get('status')
        actual_duration = data.get('actual_duration')
        notes = data.get('notes', '')
        
        with get_cached_connection() as conn:
            cursor = conn.cursor(dictionary=True)
            
            # Check if session belongs to user
            cursor.execute("SELECT * FROM study_sessions WHERE id = %s AND user_id = %s", (session_id, user_id))
            session = cursor.fetchone()
            
            if not session:
                return create_error_response("Study session not found", 404)
            
            # Update session
            update_fields = []
            params = []
            
            if status:
                update_fields.append("status = %s")
                params.append(status)
                
            if actual_duration:
                update_fields.append("actual_duration = %s")
                params.append(actual_duration)
                
            if notes:
                update_fields.append("notes = %s")
                params.append(notes)
                
            if status == 'completed':
                update_fields.append("completed_at = %s")
                params.append(datetime.now())
            
            if update_fields:
                query = f"UPDATE study_sessions SET {', '.join(update_fields)} WHERE id = %s AND user_id = %s"
                cursor.execute(query, params + [session_id, user_id])
                conn.commit()
            
            update_data = {
                'session_id': session_id,
                'status': status,
                'updated_at': datetime.now().isoformat()
            }
            return format_api_response(update_data, include_legacy_fields=update_data)
            
    except Exception as e:
        logger.error(f"Error updating study session: {str(e)}")
        return create_error_response("Failed to update study session", 500)

@superapp_bp.route('/api/superapp/academic-tools/assignments', methods=['GET'])
@require_api_key
@require_auth
def get_assignments():
    """Get user assignments/tasks"""
    try:
        user_id = request.current_user['user_id']
        status = request.args.get('status', 'all')  # all, pending, completed, overdue
        
        with get_cached_connection() as conn:
            cursor = conn.cursor(dictionary=True)
            
            base_query = """
            SELECT id, title, description, subject, due_date, priority, status, 
                   created_at, completed_at
            FROM user_assignments 
            WHERE user_id = %s
            """
            
            params = [user_id]
            
            if status != 'all':
                if status == 'overdue':
                    base_query += " AND status = 'pending' AND due_date < %s"
                    params.append(datetime.now())
                else:
                    base_query += " AND status = %s"
                    params.append(status)
            
            base_query += " ORDER BY due_date ASC, priority DESC, created_at DESC"
            
            cursor.execute(base_query, params)
            assignments = cursor.fetchall()
            
            formatted_assignments = []
            for assignment in assignments:
                # Check if overdue
                is_overdue = (assignment['status'] == 'pending' and 
                            assignment['due_date'] and 
                            assignment['due_date'] < datetime.now())
                
                formatted_assignments.append({
                    'id': assignment['id'],
                    'title': assignment['title'],
                    'description': assignment['description'],
                    'subject': assignment['subject'],
                    'due_date': assignment['due_date'].isoformat() if assignment['due_date'] else None,
                    'priority': assignment['priority'],
                    'status': assignment['status'],
                    'is_overdue': is_overdue,
                    'created_at': assignment['created_at'].isoformat() if assignment['created_at'] else None,
                    'completed_at': assignment['completed_at'].isoformat() if assignment['completed_at'] else None
                })
            
            return format_api_response({'assignments': formatted_assignments}, include_legacy_fields={'assignments': formatted_assignments})
            
    except Exception as e:
        logger.error(f"Error getting assignments: {str(e)}")
        return create_error_response("Failed to fetch assignments", 500)

@superapp_bp.route('/api/superapp/academic-tools/assignments', methods=['POST'])
@require_api_key
@require_auth
def create_assignment():
    """Create a new assignment"""
    try:
        user_id = request.current_user['user_id']
        data = request.get_json()
        
        title = data.get('title', '').strip()
        description = data.get('description', '')
        subject = data.get('subject', '')
        due_date = data.get('due_date')
        priority = data.get('priority', 'medium')
        
        if not title:
            return create_error_response("Assignment title is required", 400)
        
        with get_cached_connection() as conn:
            cursor = conn.cursor()
            
            query = """
            INSERT INTO user_assignments (user_id, title, description, subject, due_date, priority, status, created_at)
            VALUES (%s, %s, %s, %s, %s, %s, 'pending', %s)
            """
            
            cursor.execute(query, (user_id, title, description, subject, due_date, priority, datetime.now()))
            assignment_id = cursor.lastrowid
            conn.commit()
            
            assignment_data = {
                'id': assignment_id,
                'title': title,
                'description': description,
                'subject': subject,
                'due_date': due_date,
                'priority': priority,
                'status': 'pending',
                'created_at': datetime.now().isoformat()
            }
            return format_api_response(assignment_data, include_legacy_fields=assignment_data)
            
    except Exception as e:
        logger.error(f"Error creating assignment: {str(e)}")
        return create_error_response("Failed to create assignment", 500)

# ============================================================================
# FINANCIAL TOOLS SECTION
# ============================================================================

@superapp_bp.route('/api/superapp/financial-tools/emi-calculator', methods=['POST'])
@require_api_key
def calculate_emi():
    """Calculate EMI for loan"""
    try:
        data = request.get_json()
        principal = float(data.get('principal', 0))
        annual_rate = float(data.get('annual_rate', 0))
        tenure_months = int(data.get('tenure_months', 0))
        
        if principal <= 0 or annual_rate < 0 or tenure_months <= 0:
            return create_error_response("Invalid input values", 400)
        
        # Convert annual rate to monthly rate
        monthly_rate = annual_rate / 100 / 12
        
        # EMI calculation formula
        if monthly_rate > 0:
            emi = (principal * monthly_rate * (1 + monthly_rate) ** tenure_months) / ((1 + monthly_rate) ** tenure_months - 1)
        else:
            emi = principal / tenure_months
        
        total_amount = emi * tenure_months
        total_interest = total_amount - principal
        
        emi_data = {
            'emi': round(emi, 2),
            'total_amount': round(total_amount, 2),
            'total_interest': round(total_interest, 2),
            'principal': principal,
            'annual_rate': annual_rate,
            'monthly_rate': round(monthly_rate * 100, 4),
            'tenure_months': tenure_months,
            'tenure_years': round(tenure_months / 12, 1)
        }
        return format_api_response(emi_data, include_legacy_fields=emi_data)
        
    except ValueError as e:
        return create_error_response("Invalid numeric input", 400)
    except Exception as e:
        logger.error(f"Error calculating EMI: {str(e)}")
        return create_error_response("Failed to calculate EMI", 500)

@superapp_bp.route('/api/superapp/financial-tools/budget-categories', methods=['GET'])
@require_api_key
@require_auth
def get_budget_categories():
    """Get user's budget categories or default ones"""
    try:
        user_id = request.current_user['user_id']
        
        with get_cached_connection() as conn:
            cursor = conn.cursor(dictionary=True)
            
            # First check if user has custom categories
            cursor.execute("""
                SELECT id, name, icon, color, monthly_limit 
                FROM budget_categories 
                WHERE user_id = %s
                ORDER BY name
            """, (user_id,))
            
            categories = cursor.fetchall()
            
            # If no custom categories, return defaults
            if not categories:
                cursor.execute("""
                    SELECT id, name, icon, color, monthly_limit 
                    FROM budget_categories 
                    WHERE is_default = TRUE
                    ORDER BY name
                """)
                categories = cursor.fetchall()
            
            return format_api_response({'categories': categories}, include_legacy_fields={'categories': categories})
            
    except Exception as e:
        logger.error(f"Error getting budget categories: {str(e)}")
        return create_error_response("Failed to fetch budget categories", 500)

@superapp_bp.route('/api/superapp/financial-tools/budget-expenses', methods=['POST'])
@require_api_key
@require_auth
def add_expense():
    """Add a new expense"""
    try:
        user_id = request.current_user['user_id']
        data = request.get_json()
        
        category_id = data.get('category_id')
        amount = float(data.get('amount', 0))
        description = data.get('description', '')
        expense_date = data.get('expense_date', datetime.now().date())
        
        if not category_id or amount <= 0:
            return create_error_response("Category and positive amount are required", 400)
        
        with get_cached_connection() as conn:
            cursor = conn.cursor()
            
            query = """
            INSERT INTO budget_expenses (user_id, category_id, amount, description, expense_date, created_at)
            VALUES (%s, %s, %s, %s, %s, %s)
            """
            
            cursor.execute(query, (user_id, category_id, amount, description, expense_date, datetime.now()))
            expense_id = cursor.lastrowid
            conn.commit()
            
            expense_data = {
                'id': expense_id,
                'category_id': category_id,
                'amount': amount,
                'description': description,
                'expense_date': expense_date.isoformat() if hasattr(expense_date, 'isoformat') else expense_date,
                'created_at': datetime.now().isoformat()
            }
            return format_api_response(expense_data, include_legacy_fields=expense_data)
            
    except ValueError as e:
        return create_error_response("Invalid amount", 400)
    except Exception as e:
        logger.error(f"Error adding expense: {str(e)}")
        return create_error_response("Failed to add expense", 500)

# ============================================================================
# STUDY AIDS SECTION
# ============================================================================

@superapp_bp.route('/api/superapp/study-aids/dictionary', methods=['GET'])
@require_api_key
def dictionary_lookup():
    """Dictionary word lookup with caching"""
    try:
        word = request.args.get('word', '').lower().strip()
        
        if not word:
            return create_error_response("Word parameter is required", 400)
        
        with get_cached_connection() as conn:
            cursor = conn.cursor(dictionary=True)
            
            # Check cache first
            cursor.execute("SELECT word, phonetic, definitions, last_updated FROM dictionary_cache WHERE word = %s", (word,))
            cached_result = cursor.fetchone()
            
            if cached_result:
                dict_data = {
                    'word': cached_result['word'],
                    'phonetic': cached_result['phonetic'],
                    'definitions': json.loads(cached_result['definitions']) if cached_result['definitions'] else [],
                    'cached': True,
                    'last_updated': cached_result['last_updated'].isoformat() if cached_result['last_updated'] else None
                }
                return format_api_response(dict_data, include_legacy_fields=dict_data)
        
        # Mock dictionary data for now - can be replaced with actual dictionary API
        mock_definitions = {
            'study': {
                'word': 'study',
                'phonetic': '/ˈstʌdi/',
                'definitions': [
                    {
                        'part_of_speech': 'noun',
                        'definition': 'The devotion of time and attention to acquiring knowledge on an academic subject.',
                        'example': 'The study of English literature'
                    },
                    {
                        'part_of_speech': 'verb',
                        'definition': 'Devote time and attention to learning about (a subject).',
                        'example': 'I studied French for two years'
                    }
                ]
            },
            'education': {
                'word': 'education',
                'phonetic': '/ˌɛdʒʊˈkeɪʃən/',
                'definitions': [
                    {
                        'part_of_speech': 'noun',
                        'definition': 'The process of receiving or giving systematic instruction, especially at a school or university.',
                        'example': 'A new system of public education'
                    }
                ]
            },
            'learn': {
                'word': 'learn',
                'phonetic': '/lɜːn/',
                'definitions': [
                    {
                        'part_of_speech': 'verb',
                        'definition': 'Acquire knowledge or skills through experience, study, or by being taught.',
                        'example': 'They learn to read and write'
                    }
                ]
            }
        }
        
        if word in mock_definitions:
            result = mock_definitions[word]
            
            # Cache the result
            try:
                with get_cached_connection() as conn:
                    cursor = conn.cursor()
                    cursor.execute("""
                        INSERT INTO dictionary_cache (word, phonetic, definitions, last_updated)
                        VALUES (%s, %s, %s, %s)
                        ON DUPLICATE KEY UPDATE
                        phonetic = VALUES(phonetic),
                        definitions = VALUES(definitions),
                        last_updated = VALUES(last_updated)
                    """, (word, result['phonetic'], json.dumps(result['definitions']), datetime.now()))
                    conn.commit()
            except Exception as cache_error:
                logger.warning(f"Failed to cache dictionary result: {cache_error}")
            
            return format_api_response(result, include_legacy_fields=result)
        else:
            return format_api_response({
                'word': word,
                'message': f'Definition for "{word}" not found in our database.',
                'suggestions': ['Please check spelling or try a simpler form of the word.']
            }, include_legacy_fields={
                'word': word,
                'message': f'Definition for "{word}" not found in our database.',
                'suggestions': ['Please check spelling or try a simpler form of the word.']
            })
            
    except Exception as e:
        logger.error(f"Error in dictionary lookup: {str(e)}")
        return create_error_response("Failed to lookup word", 500)

@superapp_bp.route('/api/superapp/study-aids/unit-converter', methods=['POST'])
@require_api_key
def convert_units():
    """Unit conversion tool"""
    try:
        data = request.get_json()
        value = float(data.get('value', 0))
        from_unit = data.get('from_unit', '').lower()
        to_unit = data.get('to_unit', '').lower()
        category = data.get('category', 'length')
        
        # Conversion factors to base units
        conversions = {
            'length': {
                'meter': 1.0, 'm': 1.0,
                'kilometer': 0.001, 'km': 0.001,
                'centimeter': 100.0, 'cm': 100.0,
                'millimeter': 1000.0, 'mm': 1000.0,
                'inch': 39.3701, 'foot': 3.28084, 'ft': 3.28084,
                'yard': 1.09361, 'mile': 0.000621371
            },
            'weight': {
                'kilogram': 1.0, 'kg': 1.0,
                'gram': 1000.0, 'g': 1000.0,
                'pound': 2.20462, 'lb': 2.20462,
                'ounce': 35.274, 'oz': 35.274
            },
            'temperature': {
                'celsius': lambda x: x,
                'fahrenheit': lambda x: (x * 9/5) + 32,
                'kelvin': lambda x: x + 273.15
            },
            'volume': {
                'liter': 1.0, 'l': 1.0,
                'milliliter': 1000.0, 'ml': 1000.0,
                'gallon': 0.264172, 'quart': 1.05669,
                'pint': 2.11338, 'cup': 4.22675
            }
        }
        
        if category not in conversions:
            return create_error_response(f"Unsupported category: {category}", 400)
        
        if from_unit not in conversions[category] or to_unit not in conversions[category]:
            return create_error_response(f"Unsupported units for {category}", 400)
        
        if category == 'temperature':
            # Special handling for temperature
            celsius = value
            if from_unit == 'fahrenheit':
                celsius = (value - 32) * 5/9
            elif from_unit == 'kelvin':
                celsius = value - 273.15
            
            result = conversions[category][to_unit](celsius)
        else:
            # Standard unit conversion
            base_value = value / conversions[category][from_unit]
            result = base_value * conversions[category][to_unit]
        
        conversion_data = {
            'original_value': value,
            'from_unit': from_unit,
            'to_unit': to_unit,
            'result': round(result, 6),
            'category': category,
            'formula_used': f"1 {from_unit} = {conversions[category].get(from_unit, 'N/A')} base units" if category != 'temperature' else 'Temperature conversion'
        }
        return format_api_response(conversion_data, include_legacy_fields=conversion_data)
        
    except ValueError as e:
        return create_error_response("Invalid numeric input", 400)
    except Exception as e:
        logger.error(f"Error in unit conversion: {str(e)}")
        return create_error_response("Failed to convert units", 500)

# ============================================================================
# PRODUCTIVITY SECTION
# ============================================================================

@superapp_bp.route('/api/superapp/productivity/tasks', methods=['GET'])
@require_api_key
@require_auth
def get_tasks():
    """Get user tasks"""
    try:
        user_id = request.current_user['user_id']
        status = request.args.get('status', 'all')  # pending, completed, all
        limit = request.args.get('limit', default=50, type=int)
        
        with get_cached_connection() as conn:
            cursor = conn.cursor(dictionary=True)
            
            base_query = """
            SELECT id, title, description, status, priority, due_date, created_at, updated_at
            FROM user_tasks 
            WHERE user_id = %s
            """
            
            params = [user_id]
            
            if status and status != 'all':
                base_query += " AND status = %s"
                params.append(status)
            
            base_query += " ORDER BY priority DESC, due_date ASC, created_at DESC LIMIT %s"
            params.append(limit)
            
            cursor.execute(base_query, params)
            tasks = cursor.fetchall()
            
            formatted_tasks = []
            for task in tasks:
                formatted_tasks.append({
                    'id': task['id'],
                    'title': task['title'],
                    'description': task['description'],
                    'status': task['status'],
                    'priority': task['priority'],
                    'due_date': task['due_date'].isoformat() if task['due_date'] else None,
                    'created_at': task['created_at'].isoformat() if task['created_at'] else None,
                    'updated_at': task['updated_at'].isoformat() if task['updated_at'] else None
                })
            
            return format_api_response({'tasks': formatted_tasks}, include_legacy_fields={'tasks': formatted_tasks})
            
    except Exception as e:
        logger.error(f"Error getting tasks: {str(e)}")
        return create_error_response("Failed to fetch tasks", 500)

@superapp_bp.route('/api/superapp/productivity/tasks', methods=['POST'])
@require_api_key
@require_auth
def create_task():
    """Create a new task"""
    try:
        user_id = request.current_user['user_id']
        data = request.get_json()
        
        title = data.get('title', '').strip()
        description = data.get('description', '')
        priority = data.get('priority', 'medium')
        due_date = data.get('due_date')
        
        if not title:
            return create_error_response("Task title is required", 400)
        
        with get_cached_connection() as conn:
            cursor = conn.cursor()
            
            query = """
            INSERT INTO user_tasks (user_id, title, description, status, priority, due_date, created_at)
            VALUES (%s, %s, %s, 'pending', %s, %s, %s)
            """
            
            cursor.execute(query, (user_id, title, description, priority, due_date, datetime.now()))
            task_id = cursor.lastrowid
            conn.commit()
            
            task_data = {
                'id': task_id,
                'title': title,
                'description': description,
                'status': 'pending',
                'priority': priority,
                'due_date': due_date,
                'created_at': datetime.now().isoformat()
            }
            return format_api_response(task_data, include_legacy_fields=task_data)
            
    except Exception as e:
        logger.error(f"Error creating task: {str(e)}")
        return create_error_response("Failed to create task", 500)

@superapp_bp.route('/api/superapp/productivity/tasks/<int:task_id>', methods=['PUT'])
@require_api_key
@require_auth
def update_task(task_id):
    """Update a task"""
    try:
        user_id = request.current_user['user_id']
        data = request.get_json()
        
        with get_cached_connection() as conn:
            cursor = conn.cursor()
            
            # Check if task belongs to user
            cursor.execute("SELECT id FROM user_tasks WHERE id = %s AND user_id = %s", (task_id, user_id))
            if not cursor.fetchone():
                return create_error_response("Task not found", 404)
            
            # Update fields
            update_fields = []
            params = []
            
            for field in ['title', 'description', 'status', 'priority', 'due_date']:
                if field in data:
                    update_fields.append(f"{field} = %s")
                    params.append(data[field])
            
            if update_fields:
                update_fields.append("updated_at = %s")
                params.append(datetime.now())
                
                query = f"UPDATE user_tasks SET {', '.join(update_fields)} WHERE id = %s AND user_id = %s"
                cursor.execute(query, params + [task_id, user_id])
                conn.commit()
            
            task_update = {
                'id': task_id,
                'updated_at': datetime.now().isoformat(),
                'message': 'Task updated successfully'
            }
            return format_api_response(task_update, include_legacy_fields=task_update)
            
    except Exception as e:
        logger.error(f"Error updating task: {str(e)}")
        return create_error_response("Failed to update task", 500)

@superapp_bp.route('/api/superapp/productivity/tasks/<int:task_id>', methods=['DELETE'])
@require_api_key
@require_auth
def delete_task(task_id):
    """Delete a task"""
    try:
        user_id = request.current_user['user_id']
        
        with get_cached_connection() as conn:
            cursor = conn.cursor()
            
            cursor.execute("DELETE FROM user_tasks WHERE id = %s AND user_id = %s", (task_id, user_id))
            
            if cursor.rowcount == 0:
                return create_error_response("Task not found", 404)
            
            conn.commit()
            
            delete_data = {
                'message': 'Task deleted successfully',
                'deleted_at': datetime.now().isoformat()
            }
            return format_api_response(delete_data, include_legacy_fields=delete_data)
            
    except Exception as e:
        logger.error(f"Error deleting task: {str(e)}")
        return create_error_response("Failed to delete task", 500)

# ============================================================================
# AI INTEGRATION ENDPOINTS
# ============================================================================

@superapp_bp.route('/api/superapp/ai-assistant', methods=['POST'])
@require_api_key
@require_auth
def get_ai_assistance():
    """Get AI assistance for SuperApp tools using existing AI chat system"""
    try:
        user_id = request.current_user['user_id']
        data = request.get_json()
        
        tool_context = data.get('tool_context', 'general')  # academic, financial, study, productivity
        user_message = data.get('message', '')
        
        if not user_message:
            return create_error_response("Message is required", 400)
        
        # Map tool context to AI chat modes
        mode_mapping = {
            'academic': 'tutor',
            'financial': 'general', 
            'study': 'tutor',
            'productivity': 'general',
            'general': 'general'
        }
        
        mode = mode_mapping.get(tool_context, 'general')
        
        # Create a specialized prompt based on context
        context_prompts = {
            'academic': f"As an academic tutor, help with this request: {user_message}",
            'financial': f"As a financial advisor, help calculate or explain: {user_message}",
            'study': f"As a study assistant, help with: {user_message}",
            'productivity': f"As a productivity coach, help with task management: {user_message}"
        }
        
        enhanced_message = context_prompts.get(tool_context, user_message)
        
        # Use existing AI chat system (simplified integration)
        # This would typically call the AI chat routes internally
        ai_response_data = {
            'response': f"AI Assistant Response for {tool_context}: I can help you with {user_message}. This would integrate with the existing AI chat system.",
            'tool_context': tool_context,
            'mode': mode,
            'timestamp': datetime.now().isoformat()
        }
        return format_api_response(ai_response_data, include_legacy_fields=ai_response_data)
        
    except Exception as e:
        logger.error(f"Error getting AI assistance: {str(e)}")
        return create_error_response("Failed to get AI assistance", 500)