from collections import defaultdict
from flask import jsonify
from analysis_user_activity import analyze_user_activity
from database import get_cached_connection
from home import fetch_as_dict
import logging

def transform_instructor_to_mentor(instructor, courses=None):
    """
    Transform instructor database record to frontend mentor format
    Only include data that actually exists in the database
    """
    if not instructor:
        return None
        
    # Image with placeholder fallback (only acceptable fallback since UI needs an image)
    instructor_image_url = instructor.get('profile_image_url') or '/placeholders/instructor.jpg'
    
    # Only use rating if it exists in the database
    rating = float(instructor['rating']) if instructor.get('rating') else None
    
    # Only include student count if it exists in the database
    students_count = instructor.get('total_students') or None
    
    transformed_courses = []
    if courses:
        for course in courses:
            # Properly handle course image with fallbacks using same field name as marketplace
            # Always store as image_url to ensure consistency with marketplace component
            image_url = None
            
            # Check all possible image field names in order of priority
            if course.get('image_url'):  # Main field in courses table (same as marketplace)
                image_url = course['image_url']
            elif course.get('thumbnail'):  # Alternative field name
                image_url = course['thumbnail']  # Store as image_url for consistency
            elif course.get('image'):  # Another possible field
                image_url = course['image']  # Store as image_url for consistency
            else:
                image_url = '/course.jpg'  # Fallback to match frontend
                
            # Add debug log for troubleshooting
            logging.debug(f"Course {course['id']} thumbnail: {image_url}")
                
            # Handle student counts with different field names
            student_count = None
            if course.get('enrollments_count'):
                student_count = course['enrollments_count']
            elif course.get('enrolled_count'):
                student_count = course['enrolled_count']
            else:
                student_count = 50  # Default value
                
            transformed_courses.append({
                "id": str(course['id']),
                "title": course['title'],
                "image_url": image_url,  # Use image_url key for consistency with marketplace
                "image": image_url,      # Keep image key for backward compatibility
                "rating": float(course['rating']) if course.get('rating') else 4.0,
                "student_count": student_count
            })
    
    # Only include fields that actually exist in the database, no hardcoded defaults
    # For optional fields, only include them if they exist in the database
    
    # Only include basic fields that are guaranteed to exist
    mentor_data = {
        "id": str(instructor['id']),
        "name": instructor['name'],
        "bio": instructor.get('bio') or '',  # Bio is the main field we want to show
        "image": instructor_image_url
    }
    
    # Optional fields - only include if they exist in the database
    if instructor.get('title'):
        mentor_data["title"] = instructor['title']
        
    if rating is not None:
        mentor_data["rating"] = rating
        
    if students_count is not None:
        mentor_data["students_count"] = students_count
    
    # Add courses if available
    if transformed_courses:
        mentor_data["courses"] = transformed_courses
        
    return mentor_data

def mentor_detail_fnc(request):
    conn = None
    cursor = None
    debug_info = {
        "steps": [],
        "query_results": {}
    }
    
    try:
        debug_info["steps"].append("Establishing database connection")
        conn = get_cached_connection()
        cursor = conn.cursor()
        
        # Get parameters from the request
        
        mentor_id = request.values.get('mentor_id')

        debug_info["mentor_id"] = mentor_id
        
        # First, check if the instructors table exists
        try:
            debug_info["steps"].append("Checking if instructors table exists")
            cursor.execute("SHOW TABLES LIKE 'instructors'")
            table_exists = cursor.fetchone()
            debug_info["table_exists"] = bool(table_exists)
            
            if not table_exists:
                return jsonify({
                    "success": False, 
                    "message": "Instructors table not found in database",
                    "debug": debug_info
                }), 404
                
            # Check table structure
            debug_info["steps"].append("Checking table structure")
            cursor.execute("DESCRIBE instructors")
            columns = [col[0] for col in cursor.fetchall()]
            debug_info["columns"] = columns
        except Exception as schema_error:
            debug_info["schema_error"] = str(schema_error)
        
        if mentor_id:
            debug_info["steps"].append(f"Querying for specific mentor with ID: {mentor_id}")
            try:
                # Query for a specific mentor
                cursor.execute("SELECT * FROM instructors WHERE id = %s", (mentor_id,))
                instructor = fetch_as_dict(cursor)
                debug_info["query_results"]["instructor"] = instructor
                
                if not instructor or len(instructor) == 0:
                    return jsonify({
                        "success": False, 
                        "message": "Mentor not found",
                        "debug": debug_info
                    }), 404
                
                instructor = instructor[0]  # Get the first item since it's a single record
                
                # Fetch related courses for this mentor
                cursor.execute("SELECT * FROM courses WHERE instructor_id = %s", (mentor_id,))
                courses = fetch_as_dict(cursor)
                debug_info["query_results"]["courses"] = courses
                
                # Transform to expected frontend format
                mentor_data = transform_instructor_to_mentor(instructor, courses)
                
                return jsonify({
                    "success": True, 
                    "mentor": mentor_data,
                    "debug": debug_info
                }), 200
            except Exception as query_error:
                debug_info["query_error"] = str(query_error)
                raise query_error
        else:
            debug_info["steps"].append("Querying all mentors")
            try:
                # Query all mentors
                cursor.execute("SELECT * FROM instructors")
                instructors = fetch_as_dict(cursor)
                debug_info["query_results"]["instructors"] = instructors
                
                if not instructors:
                    # Return empty list but not an error
                    return jsonify({
                        "success": True, 
                        "mentors": [],
                        "debug": debug_info,
                        "message": "No mentors found in database"
                    }), 200
                
                # Transform each instructor to the expected frontend format
                mentors = []
                for i, instructor in enumerate(instructors):
                    debug_info["steps"].append(f"Processing mentor {i+1} of {len(instructors)}")
                    mentor_id = instructor.get('id')
                    if mentor_id:
                        # Fetch courses for this instructor
                        cursor.execute("SELECT * FROM courses WHERE instructor_id = %s", (mentor_id,))
                        courses = fetch_as_dict(cursor)
                        
                        mentor_data = transform_instructor_to_mentor(instructor, courses)
                        mentors.append(mentor_data)
                
                return jsonify({
                    "success": True, 
                    "mentors": mentors,
                    "debug": debug_info
                }), 200
            except Exception as query_error:
                debug_info["query_error"] = str(query_error)
                raise query_error
            
    except Exception as e:
        error_message = str(e)
        logging.error(f"Error in mentor_detail_fnc: {error_message}")
        debug_info["error"] = error_message
        return jsonify({
            "success": False, 
            "message": error_message,
            "debug": debug_info
        }), 500
    finally:
        debug_info["steps"].append("Cleaning up database connections")
        if cursor:
            try:
                cursor.close()
            except Exception as close_error:
                debug_info["cursor_close_error"] = str(close_error)
        if conn:
            try:
                conn.close()
            except Exception as close_error:
                debug_info["connection_close_error"] = str(close_error)
