"""
Video related routes
"""
import logging
from flask import  g

from datetime import datetime
from flask import Blueprint, request, make_response, jsonify
from utils import (require_api_key, add_keep_alive, format_api_response, 
                   encrypt_data, CustomJSONEncoder, create_error_response, format_validation_error)
from auth.jwt_manager import require_auth, require_user_access
from videos_get import get_videos
from course.video_details import insert_discussion, video_details
from course.video_track import video_tracking


logger = logging.getLogger(__name__)
video_bp = Blueprint('video', __name__)


@video_bp.route('/get_videos', methods=['POST', 'GET'])
@require_api_key
@require_auth
@require_user_access
def get_vid():
    response = make_response(get_videos(request))
    return response


@video_bp.route('/video_detail', methods=['POST', 'GET'])
@require_api_key
@require_auth
@require_user_access
def video_detail():
    print("Received request for video details")
    response = make_response(video_details(request))
    # print("Response data:", response.get_data())
    return add_keep_alive(response)


@video_bp.route('/video_track', methods=['POST'])
@require_api_key
@require_auth
@require_user_access
def video_track():
    response = make_response(video_tracking(request))
    return add_keep_alive(response)


@video_bp.route('/submit_feedback', methods=['POST'])
@require_api_key
def submit_feedback():
    try:
        # Get form data
        # user_id = request.form.get("user_id")
        user_id = getattr(g, 'current_user_id', None) or request.values.get('user_id')

        course_id = request.form.get("course_id")
        video_id = request.form.get("video_id")
        rating = request.form.get("rating")
        review_text = request.form.get("feedback_text")
        
        # Log received data for debugging
        logger.info("Feedback submission: user_id={}, course_id={}, video_id={}, rating={}".format(user_id, course_id, video_id, rating))

        # Validate required fields - only need either course_id or video_id, not necessarily both
        if not user_id or not rating or not review_text:
            return format_validation_error(
                {"user_id": "required" if not user_id else None, "rating": "required" if not rating else None, "feedback_text": "required" if not review_text else None},
                "Missing required fields"
            )
            
        if not course_id and not video_id:
            return format_validation_error(
                {"course_id": "required (or video_id)", "video_id": "required (or course_id)"},
                "Either course_id or video_id must be provided"
            )

        created_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        feedback_id = None
        
        # Use database connection
        from database import get_cached_connection
        conn = get_cached_connection()
        cursor = None
        try:
            cursor = conn.cursor()
            
            # Insert review into database
            query = """
            INSERT INTO course_reviews (course_id, user_id, rating, review, created_at, video_id)
            VALUES (%s, %s, %s, %s, %s, %s)
            """
            cursor.execute(query, (course_id, user_id, rating,
                        review_text, created_at, video_id))
            conn.commit()

            feedback_id = cursor.lastrowid
            
            return jsonify(format_api_response(
                data={"feedback_id": feedback_id},
                message="Feedback submitted successfully",
                include_legacy_fields={"status": "success", "feedback_id": feedback_id}
            ))
        finally:
            # Ensure resources are properly cleaned up
            if cursor and hasattr(cursor, 'close'):
                cursor.close()
            if conn and hasattr(conn, 'close'):
                conn.close()

    except Exception as e:
        logger.error("Error in submit_feedback: {}".format(str(e)))
        return create_error_response(
            "Failed to submit feedback",
            status_code=500,
            error_code="FEEDBACK_ERROR",
            error_details=str(e) if logger.level == logging.DEBUG else None
        )


@video_bp.route('/user_all_videos', methods=['POST', 'GET'])
@require_auth
@require_user_access
def user_all_videos():
    """Fetch all videos for a user across all their courses in a single request"""
    try:
        user_id = getattr(g, 'current_user_id', None) or request.values.get('user_id')
        
        if not user_id:
            return format_validation_error(
                {"user_id": "required"},
                "User ID is required"
            )
        
        # Create database connection
        from database import get_cached_connection
        conn = get_cached_connection()
        cursor = conn.cursor(dictionary=True)
        
        # First get all courses the user is enrolled in
        cursor.execute("""
            SELECT c.id as course_id, c.title as course_title 
            FROM courses c
            JOIN enrollments e ON c.id = e.course_id
            WHERE e.user_id = %s AND e.payment_status IN ('free', 'paid')
        """, (user_id,))
        
        courses = cursor.fetchall()
        print(f"Found {len(courses)} courses for user {user_id}")
        
        # Array to store all videos
        all_videos = []
        
        # For each course, get all videos
        for course in courses:
            course_id = course['course_id']
            course_title = course['course_title']
            print(f"Fetching videos for course {course_id}: {course_title}")
            
            # Get videos for this course - Add all possible thumbnail fields
            cursor.execute("""
                SELECT 
                    v.*, 
                    %s as course_title,
                    COALESCE(rw.watched_percentage, 0) as progress,
                    rw.time_watched as last_watched,
                    0 as is_bookmarked,
                    t.title as topic_title,
                    t.parent_topic_id,
                    t.level,
                    t.full_path,
                    v.video_url as video_url,
                    v.image_url as image_url,
                    v.image_url as thumbnail_url,
                    v.video_duration as duration
                FROM videos v
                LEFT JOIN recently_watched rw ON v.id = rw.video_id AND rw.user_id = %s
                LEFT JOIN topics t ON v.topic_id = t.id
                WHERE v.course_id = %s
                ORDER BY rw.time_watched DESC, v.updated_at DESC
            """, (course_title, user_id, course_id))
            
            course_videos = cursor.fetchall()
            print(f"  Found {len(course_videos)} videos in course {course_id}")
            
            # Process videos to handle datetime and timedelta serialization
            for video in course_videos:
                # Create a new dictionary to avoid modifying the original
                processed_video = {}
                
                # Copy all fields - we'll let the CustomJSONEncoder handle special types
                processed_video = {key: value for key, value in video.items()}
                
                # Add the processed video to our collection
                all_videos.append(processed_video)
        
        cursor.close()
        conn.close()
        
        # Sort all videos by last_watched time (most recent first) then by updated_at
        all_videos.sort(key=lambda x: (
            x.get('last_watched') or datetime.min,
            x.get('updated_at') or datetime.min
        ), reverse=True)
        
        # Log the number of videos found for debugging
        print(f"Found total of {len(all_videos)} videos across {len(courses)} courses for user {user_id}")
        
        # Use the global encrypt_data function which now handles Decimal types
        encrypted_data = encrypt_data({
            "response": "success",
            "videos": all_videos
        })
        
        response = make_response(encrypted_data)
        response.headers['Content-Type'] = 'text/plain; charset=utf-8'
        
        return add_keep_alive(response)
       
    except Exception as e:
        logger.error("Error in user_all_videos: {}".format(str(e)))
        return create_error_response(
            "Failed to retrieve videos",
            status_code=500,
            error_code="USER_VIDEOS_ERROR",
            error_details=str(e) if logger.level == logging.DEBUG else None
        )