from datetime import timedelta
from flask import jsonify

from db_utils import get_db_connection, fetch_as_dict
from database import optimized_execute
from utils import format_api_response, create_error_response
import logging

logger = logging.getLogger(__name__)


def course_details(request):
    # Request bata parameters haru nikalne
    course = request.values.get('course_id')
    user_id = request.values.get('user_id')
    
    # Connection ramrari close garne kura ensure garna context manager use garne
    with get_db_connection() as conn:
        cursor = conn.cursor()
        
        try:
            # Featured courses fetch garne
            optimized_execute(cursor, "SELECT * FROM videos WHERE course_id = %s", (course,))
            total_classes = len(fetch_as_dict(cursor))

            optimized_execute(cursor, "SELECT COUNT(*) as topic_count FROM topics WHERE course_id = %s", (course,))
            topic_count_result = fetch_as_dict(cursor)
            total_topics = topic_count_result[0]['topic_count'] if topic_count_result else 0
            
            optimized_execute(cursor, """
                SELECT 
                    id, title, video_url, type, description, credit, 
                    for_which, level, image_url, count_exercises, 
                    count_students, count_plays, count_views, count_likes, 
                    count_comments, short_description, course_id, is_live, 
                    chat_id, is_active, free, topic_id,
                    TIME_TO_SEC(video_duration) AS video_duration,
                    TIME_TO_SEC(created_at) AS created_at_seconds, 
                    TIME_TO_SEC(updated_at) AS updated_at_seconds
                FROM videos 
                WHERE course_id = %s
            """, (course,))
            total_videos = fetch_as_dict(cursor)

            optimized_execute(cursor,
                "SELECT * FROM course_reviews WHERE course_id = %s", (course,))
            reviews = fetch_as_dict(cursor)

            optimized_execute(cursor, """
                SELECT SUM(TIME_TO_SEC(video_duration)) AS total_duration 
                FROM videos 
                WHERE course_id = %s
            """, (course,))
            result = fetch_as_dict(cursor)

            optimized_execute(cursor, "SELECT *, parent_topic_id, level, full_path FROM topics WHERE course_id = %s ORDER BY level, parent_topic_id, order_sequence", (course,))
            topics = fetch_as_dict(cursor)

            # Total_duration timedelta object ho ki hoina check garne ra seconds ma convert garne
            if result and result[0]['total_duration']:
                total_duration = result[0]['total_duration']
                if isinstance(total_duration, timedelta):  # Timedelta object ho bhane
                    total_video_duration = total_duration.total_seconds()  # Seconds ma convert garne
                else:
                    total_video_duration = total_duration  # Duration pahile nai seconds ma xa bhane tei use garne
            else:
                total_video_duration = 0  # Kei duration bhettiyena bhane 0 lai default value manne

            # Final response structure banaunee
            final_response = {
                "total_classes": total_classes,
                "total_topics": total_topics,
                "total_video_duration": total_video_duration,
                "reviews": reviews,
                "topics": topics,
                "total_videos": total_videos,
            }
            # Use standard API response format
            return jsonify(format_api_response(
                data=final_response,
                message="Course details retrieved successfully"
            )), 200
            
        except Exception as e:
            logger.error(f"Error in course_details: {str(e)}")
            return create_error_response(
                "Failed to retrieve course details",
                status_code=500,
                error_code="COURSE_DETAILS_ERROR",
                error_details=str(e) if logger.level == logging.DEBUG else None
            )
        finally:
            # Exception aye pani cursor close hune ensure garne
            if cursor:
                cursor.close()
