from flask import jsonify


class Workout:
    def __init__(self, db_connection_method):
        self.execute = db_connection_method

    def get(self, person_id, workout_id):
        query = """
        SELECT 
            w.workout_id,
            w.person_id,
            p.name AS person_name,
            w.start_date,
            w.note,
            t.topset_id,
            e.exercise_id,
            e.name AS exercise_name,
            t.repetitions,
            t.weight,
            tag.tag_id,
            tag.name AS tag_name,
            tag.filter as tag_filter,
            CASE WHEN wt.workout_id IS NOT NULL THEN TRUE ELSE FALSE END AS is_selected
        FROM 
            workout w
        LEFT JOIN 
            person p ON w.person_id = p.person_id
        LEFT JOIN 
            topset t ON w.workout_id = t.workout_id
        LEFT JOIN 
            exercise e ON t.exercise_id = e.exercise_id
        LEFT JOIN 
            workout_tag wt ON w.workout_id = wt.workout_id
        LEFT JOIN 
            tag ON TRUE -- Join to get all tags
        WHERE 
            w.person_id = %s
            AND w.workout_id = %s;
        """
        data = self.execute(query, [person_id, workout_id])

        if not data:
            return {"error": "Workout not found"}, 404

        # Initialize workout dictionary
        workout_data = {
            "workout_id": data[0]["workout_id"],
            "person_id": data[0]["person_id"],
            "person_name": data[0]["person_name"],
            "start_date": data[0]["start_date"],
            "note": data[0]["note"],
            "tags": [],
            "top_sets": [],
        }
        
        # Initialize helpers for tracking unique tags and topsets
        tag_set = set()
        topsets_seen = set()

        # Process each row and add tags and topsets to workout_data
        for row in data:
            # Add all unique tags with is_selected property
            tag_id = row["tag_id"]
            if tag_id and tag_id not in tag_set:
                workout_data["tags"].append({
                    "tag_id": tag_id,
                    "tag_name": row["tag_name"],
                    "tag_filter": row["tag_filter"],
                    "person_id": person_id,
                    "is_selected": row["is_selected"]
                })
                tag_set.add(tag_id)

            # Add unique topsets based on topset_id
            topset_id = row["topset_id"]
            if topset_id and topset_id not in topsets_seen:
                workout_data["top_sets"].append({
                    "topset_id": topset_id,
                    "exercise_id": row["exercise_id"],
                    "exercise_name": row["exercise_name"],
                    "repetitions": row["repetitions"],
                    "weight": row["weight"]
                })
                topsets_seen.add(topset_id)

        return workout_data
