from flask import request, jsonify
from db_config import get_db_connection

MAX_WORKOUTS_PER_USER = 10

def get_workouts_by_user():
    try:
        user_id = request.args.get("user_id")
        if not user_id:
            return jsonify({"error": "Missing user_id"}), 400

        conn = get_db_connection()
        cursor = conn.cursor(dictionary=True)

        cursor.execute("SELECT * FROM workouts WHERE user_id = %s", (user_id,))
        workouts = cursor.fetchall()

        for workout in workouts:
            cursor.execute("""
                SELECT we.*, e.name AS exercise_name
                FROM workout_exercises we
                JOIN exercises e ON we.exercise_id = e.id
                WHERE we.workout_id = %s
                ORDER BY we.order_index ASC
            """, (workout['id'],))
            workout['exercises'] = cursor.fetchall()

        cursor.close()
        conn.close()
        return jsonify(workouts)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

def create_workout():
    try:
        data = request.json
        user_id = data.get("user_id")
        title = data.get("title")
        recovery_time = data.get("recovery_time", 60)

        if not user_id or not title:
            return jsonify({"error": "Missing user_id or title"}), 400

        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT COUNT(*) FROM workouts WHERE user_id = %s", (user_id,))
        count = cursor.fetchone()[0]

        if count >= MAX_WORKOUTS_PER_USER:
            cursor.close()
            conn.close()
            return jsonify({"error": "Workout limit reached (10 max)"}), 403

        cursor.execute("INSERT INTO workouts (user_id, title, recovery_time) VALUES (%s, %s, %s)", (user_id, title, recovery_time))
        conn.commit()
        cursor.close()
        conn.close()
        return jsonify({"status": "Workout created"}), 201
    except Exception as e:
        return jsonify({"error": str(e)}), 500

def delete_workout():
    try:
        data = request.json
        workout_id = data.get("workout_id")
        if not workout_id:
            return jsonify({"error": "Missing workout_id"}), 400

        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute("DELETE FROM workouts WHERE id = %s", (workout_id,))
        conn.commit()
        cursor.close()
        conn.close()
        return jsonify({"status": "Workout deleted"})
    except Exception as e:
        return jsonify({"error": str(e)}), 500

def modify_workout_exercise():
    try:
        data = request.json
        action = data.get("action")

        if not action or not workout_id or not exercise_id:
            return jsonify({"error": "Missing fields"}), 400

        conn = get_db_connection()
        cursor = conn.cursor()

        if action == "add":
            sets = data.get("sets", 3)
            reps = data.get("reps", 10)
            weight = data.get("weight", 0.0)
            order_index = data.get("order_index", 0)
            cursor.execute("""
                INSERT INTO workout_exercises (workout_id, exercise_id, sets, reps, weight, order_index)
                VALUES (%s, %s, %s, %s, %s, %s)
            """, (workout_id, exercise_id, sets, reps, weight, order_index))
        elif action == "remove":
            cursor.execute("DELETE FROM workout_exercises WHERE workout_id = %s AND exercise_id = %s",(workout_id, exercise_id))
        else:
            return jsonify({"error": "Invalid action"}), 400

        conn.commit()
        cursor.close()
        conn.close()
        return jsonify({"status": f"Exercise {action}ed successfully"})
    except Exception as e:
        return jsonify({"error": str(e)}), 500

def update_workout_field():
    try:
        data = request.json
        workout_id = data.get("workout_id")
        field = data.get("field")
        value = data.get("value")

        if not workout_id or not field or value is None:
            return jsonify({"error": "Missing fields"}), 400

        if field not in ["title", "recovery_time"]:
            return jsonify({"error": "Invalid field"}), 400

        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute(f"UPDATE workouts SET {field} = %s WHERE id = %s", (value, workout_id))
        conn.commit()
        cursor.close()
        conn.close()
        return jsonify({"status": "Workout updated"})
    except Exception as e:
        return jsonify({"error": str(e)}), 500
