from flask import request, jsonify
from db_config import get_db_connection

def get_muscle_cards_for_user():
    user_id = request.args.get("user_id")
    if not user_id:
        return jsonify({"error": "Missing user_id"}), 400
    try:
        conn = get_db_connection()
        cursor = conn.cursor(dictionary=True)
        cursor.execute("""
            SELECT m.name AS muscle_name, COALESCE(mc.score, 50) AS score
            FROM muscles m
            LEFT JOIN muscle_cards mc ON mc.muscle_id = m.id AND mc.user_id = %s
        """, (user_id,))
        results = cursor.fetchall()
        cursor.close()
        conn.close()
        return jsonify(results)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

def get_muscle_score():
    user_id = request.args.get("user_id")
    muscle_name = request.args.get("muscle_name")
    if not user_id or not muscle_name:
        return jsonify({"error": "Missing user_id or muscle name"}), 400
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT id FROM muscles WHERE name = %s", (muscle_name,))
        result = cursor.fetchone()
        if not result:
            return jsonify({"error": "Muscle not found"}), 404
        muscle_id = result[0]
        cursor.execute("SELECT score FROM muscle_cards WHERE user_id = %s AND muscle_id = %s", (user_id, muscle_id))
        score = cursor.fetchone()
        cursor.close()
        conn.close()
        return jsonify({
            "muscle": muscle_name,
            "score": score[0] if score else 50
        })
    except Exception as e:
        return jsonify({"error": str(e)}), 500

def set_muscle_score():
    user_id = request.json.get("user_id")
    muscle_name = request.json.get("muscle")
    score = request.json.get("score")

    if not user_id or not muscle_name or score is None:
        return jsonify({"error": "Missing user_id, muscle or score"}), 400

    try:
        score = int(score)
        if not (1 <= score <= 100):
            return jsonify({"error": "Score must be between 1 and 100"}), 400
    except ValueError:
        return jsonify({"error": "Score must be an integer"}), 400

    try:
        conn = get_db_connection()
        cursor = conn.cursor()

        cursor.execute("SELECT id FROM muscles WHERE name = %s", (muscle_name,))
        result = cursor.fetchone()
        if not result:
            return jsonify({"error": "Muscle not found"}), 404
        muscle_id = result[0]

        cursor.execute("""
            INSERT INTO muscle_cards (user_id, muscle_id, score)
            VALUES (%s, %s, %s)
            ON DUPLICATE KEY UPDATE score = VALUES(score)
        """, (user_id, muscle_id, score))

        conn.commit()
        cursor.close()
        conn.close()
        return jsonify({"message": f"Score for '{muscle_name}' updated to {score}"})
    except Exception as e:
        return jsonify({"error": str(e)}), 500

def reset_muscle_scores():
    user_id = request.json.get("user_id")
    if not user_id:
        return jsonify({"error": "Missing user_id"}), 400
    try:
        conn = get_db_connection()
        cursor = conn.cursor()

        # Fetch all muscle IDs
        cursor.execute("SELECT id FROM muscles")
        muscles = cursor.fetchall()

        for (muscle_id,) in muscles:
            cursor.execute("""
                INSERT INTO muscle_cards (user_id, muscle_id, score)
                VALUES (%s, %s, 50)
                ON DUPLICATE KEY UPDATE score = 50
            """, (user_id, muscle_id))

        conn.commit()
        cursor.close()
        conn.close()
        return jsonify({"message": "All muscle scores reset to 50"})
    except Exception as e:
        return jsonify({"error": str(e)}), 500
