from flask import jsonify
from models import RecentlyWatched, Video
from datetime import datetime
from analyze_user import analyze_user_activity

def analyse_deep(request, Video, RecentlyWatched, db):
    try:
        # Get parameters from the request
        course = request.values.get('course')
        user_id = request.values.get('user_id')

        if not user_id:
            return jsonify({"error": "User ID is missing or invalid."}), 400

        user_id = int(user_id)

        # Call the analysis function to get the analysis result
        analysis_result = analyze_user_activity(user_id)

        # Log the analysis result for debugging
        print(f"Analysis Result: {analysis_result}")  # Log the result

        if analysis_result is None:
            return jsonify({"error": "Analysis data not found for user."}), 404

        # Fetch recently watched courses with video details
        recently_watched_courses = db.session.query(
            Video.video_url, RecentlyWatched
        ).join(Video, RecentlyWatched.video_id == Video.id) \
            .filter(RecentlyWatched.user_id == user_id) \
            .order_by(RecentlyWatched.time_watched.desc()).all()

        # Convert all dates to strings
        def convert_dates(obj):
            if isinstance(obj, dict):
                return {str(key): convert_dates(value) for key, value in obj.items()}
            elif isinstance(obj, list):
                return [convert_dates(item) for item in obj]
            elif isinstance(obj, (datetime)):  # If it's a datetime
                return obj.strftime("%Y-%m-%d %H:%M:%S")  # Convert to string
            else:
                return obj

        # Prepare the response
        final_response = convert_dates({
            "user_id": user_id,
            "course": course,
            "courses_completed": analysis_result.get("courses_completed"),
            "overall_progress": analysis_result.get("overall_progress"),
            "total_learning_time": analysis_result.get("total_learning_time"),
            "today_learning_time": analysis_result.get("today_learning_time"),
            "learning_trends": analysis_result.get("learning_trends"),
            "engagement_score": analysis_result.get("engagement_score"),
            "recently_watched_courses": [
                {
                    "video_url": item.video_url,
                    "recently_watched_id": item.RecentlyWatched.id,
                    "video_id": item.RecentlyWatched.video_id,
                    "user_id": item.RecentlyWatched.user_id,
                    "time_watched": item.RecentlyWatched.time_watched.strftime("%Y-%m-%d %H:%M:%S"),
                }
                for item in recently_watched_courses
            ],
        })

        return jsonify(final_response), 200

    except Exception as e:
        return jsonify({"error": str(e)}), 400
