from mcp_server import MCPToolset
from workouts.models import Exercise, WorkoutRoutine


class WorkoutToolset(MCPToolset):
    def list_exercises(
        self,
        query: str | None = None,
        muscle: str | None = None,
        equipment: str | None = None,
        limit: int = 20,
    ) -> list[dict]:
        """List exercises in the workout catalog, optionally filtered by
        name, primary muscle, or equipment."""
        qs = Exercise.objects.all().order_by("name")
        if query:
            qs = qs.filter(name__icontains=query)
        if muscle:
            qs = qs.filter(primary_muscles__icontains=muscle)
        if equipment:
            qs = qs.filter(equipment__icontains=equipment)
        return [_exercise_to_dict(e) for e in qs[:limit]]

    def get_exercise(self, uuid: str) -> dict | None:
        """Get an exercise by UUID."""
        try:
            e = Exercise.objects.get(uuid=uuid)
        except Exercise.DoesNotExist:
            return None
        return _exercise_to_dict(e)

    def list_workout_routines(
        self, query: str | None = None, limit: int = 20
    ) -> list[dict]:
        """List workout routines, optionally filtered by title."""
        qs = WorkoutRoutine.objects.all().order_by("-created")
        if query:
            qs = qs.filter(title__icontains=query)
        return [_routine_to_dict(r) for r in qs[:limit]]

    def get_workout_routine(self, uuid: str) -> dict | None:
        """Get a workout routine by UUID."""
        try:
            r = WorkoutRoutine.objects.get(uuid=uuid)
        except WorkoutRoutine.DoesNotExist:
            return None
        return _routine_to_dict(r)


def _exercise_to_dict(e: Exercise) -> dict:
    return {
        "uuid": str(e.uuid),
        "name": e.name,
        "force": e.force,
        "level": e.level,
        "mechanic": e.mechanic,
        "equipment": e.equipment,
        "category": e.category,
        "primary_muscles": e.primary_muscles or [],
        "secondary_muscles": e.secondary_muscles or [],
        "instructions": e.instructions or [],
    }


def _routine_to_dict(r: WorkoutRoutine) -> dict:
    result = {"uuid": str(r.uuid), "title": r.title}
    if r.description:
        result["description"] = r.description
    exercises = []
    for we in r.routine_exercises.all():
        exercises.append(
            {
                "sequence": we.sequence,
                "exercise_uuid": str(we.exercise.uuid),
                "exercise_name": we.exercise.name,
                "target_sets": we.target_sets,
                "target_reps": we.target_reps,
                "target_weight_kg": we.target_weight_kg,
                "enabled": we.enabled,
            }
        )
    if exercises:
        result["planned_exercises"] = exercises
    return result
