<?php

namespace App\Console\Commands;

use App\Models\ExerciseLibrary;
use Illuminate\Console\Command;

class FixExerciseImageUrls extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'exercises:fix-image-urls {--reset : Reset all URLs using the mapping}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Fix exercise image/gif URLs to use correct GitHub raw paths with proper mapping';

    /**
     * Mapping of exercise names in DB to actual folder names in the GitHub repo
     * Based on https://github.com/yuhonas/free-exercise-db
     */
    protected array $exerciseMapping = [
        // Chest exercises
        'Press de Banca' => 'Barbell_Bench_Press_-_Medium_Grip',
        'Press de Banca Inclinado' => 'Barbell_Incline_Bench_Press_-_Medium_Grip',
        'Flexiones de Pecho' => 'Decline_Push-Up',
        'Aperturas con Mancuernas' => 'Dumbbell_Flyes',
        'Press con Mancuernas' => 'Dumbbell_Bench_Press',
        'Press con Mancuernas Sentado' => 'Dumbbell_Shoulder_Press',
        'Fondos en Paralelas' => 'Dips_-_Chest_Version',
        'Cable Crossover' => 'Cable_Crossover',
        'Press Declinado' => 'Decline_Barbell_Bench_Press',
        
        // Back exercises
        'Dominadas' => 'Chin-Up',
        'Remo con Barra' => 'Bent_Over_Barbell_Row',
        'Remo con Mancuerna' => 'One-Arm_Dumbbell_Row',
        'Jalón al Pecho' => 'Close-Grip_Front_Lat_Pulldown',
        'Peso Muerto' => 'Barbell_Deadlift',
        'Remo en Máquina' => 'Leverage_High_Row',
        'Pull-ups' => 'Chin-Up',
        'Pullover' => 'Bent-Arm_Dumbbell_Pullover',
        
        // Shoulder exercises
        'Press Militar' => 'Barbell_Shoulder_Press',
        'Press de Hombros con Mancuernas' => 'Dumbbell_Shoulder_Press',
        'Elevaciones Laterales' => 'Dumbbell_Lying_Rear_Lateral_Raise',
        'Elevaciones Frontales' => 'Front_Dumbbell_Raise',
        'Pájaros' => 'Bent_Over_Dumbbell_Rear_Delt_Raise_With_Head_On_Bench',
        'Pájaros (Rear Delt Fly)' => 'Lying_Rear_Delt_Raise',
        'Face Pull' => 'Face_Pull',
        'Encogimientos' => 'Barbell_Shrug',
        
        // Biceps exercises
        'Curl con Barra' => 'Barbell_Curl',
        'Curl con Mancuernas' => 'Dumbbell_Bicep_Curl',
        'Curl Martillo' => 'Hammer_Curls',
        'Curl Concentrado' => 'Concentration_Curls',
        'Curl en Banco Scott' => 'Machine_Preacher_Curls',
        'Curl con Cable' => 'Cable_Hammer_Curls_-_Rope_Attachment',
        
        // Triceps exercises
        'Press Francés' => 'EZ-Bar_Skullcrusher',
        'Extensión de Tríceps en Polea' => 'Cable_One_Arm_Tricep_Extension',
        'Extensión de Tríceps Sobre la Cabeza' => 'Dumbbell_One-Arm_Triceps_Extension',
        'Fondos en Banco' => 'Bench_Dips',
        'Patada de Tríceps' => 'Dumbbell_Tricep_Extension_-Pronated_Grip',
        'Press Cerrado' => 'Close-Grip_Barbell_Bench_Press',
        
        // Leg exercises
        'Sentadilla' => 'Barbell_Full_Squat',
        'Sentadilla con Barra' => 'Barbell_Squat',
        'Sentadilla Goblet' => 'Goblet_Squat',
        'Prensa de Piernas' => 'Leg_Press',
        'Extensión de Cuádriceps' => 'Leg_Extensions',
        'Curl de Piernas' => 'Lying_Leg_Curls',
        'Curl de Piernas Acostado' => 'Lying_Leg_Curls',
        'Zancadas' => 'Dumbbell_Lunges',
        'Peso Muerto Rumano' => 'Barbell_Deadlift',
        'Hip Thrust' => 'Barbell_Hip_Thrust',
        'Puente de Glúteos' => 'Butt_Lift_Bridge',
        'Elevación de Talones' => 'Calf_Press_On_The_Leg_Press_Machine',
        'Elevación de Talones de Pie' => 'Donkey_Calf_Raises',
        'Elevación de Talones Sentado' => 'Barbell_Seated_Calf_Raise',
        'Sentadilla Búlgara' => 'Dumbbell_Rear_Lunge',
        
        // Abs exercises
        'Crunch' => 'Crunches',
        'Crunch Abdominal' => 'Crunches',
        'Crunch en Máquina' => 'Ab_Crunch_Machine',
        'Plancha' => 'Bodyweight_Flyes', // No hay Plank, usar similar
        'Elevación de Piernas' => 'Hanging_Leg_Raise',
        'Elevación de Piernas Colgado' => 'Hanging_Leg_Raise',
        'Abdominales en Polea' => 'Cable_Crunch',
        'Russian Twist' => 'Cable_Russian_Twists',
        'Mountain Climbers' => 'Mountain_Climbers',
        'Dead Bug' => 'Dead_Bug',
        
        // Cardio
        'Cinta de Correr' => 'Jogging_Treadmill',
        'Bicicleta Estática' => 'Bicycling_Stationary',
        'Elíptica' => 'Elliptical_Trainer',
        'Saltar la Cuerda' => 'Fast_Skipping',
        'Salto de Cuerda' => 'Fast_Skipping',
        'Burpees' => 'Frog_Hops', // No hay Burpee exacto
        'Jumping Jacks' => 'Freehand_Jump_Squat', // Usar similar
        'High Knees' => 'High_Cable_Curls', // Usar similar cardio
        'Box Jumps' => 'Front_Box_Jump',
        
        // Stretching
        'Estiramiento de Cuádriceps' => 'On-Your-Back_Quad_Stretch',
        'Estiramiento de Isquiotibiales' => 'Hamstring_Stretch',
        'Estiramiento de Pecho en Puerta' => 'Chest_And_Front_Of_Shoulder_Stretch',
        'Cat-Cow Stretch' => 'Cat_Stretch',
        'Hip Flexor Stretch' => 'Kneeling_Hip_Flexor',
    ];

    /**
     * Execute the console command.
     */
    public function handle(): int
    {
        $this->info('Fixing exercise image URLs with proper mapping...');
        
        // The correct base URL for the exercise database
        $baseUrl = 'https://raw.githubusercontent.com/yuhonas/free-exercise-db/main/exercises/';
        
        // Get all exercises with gif_url
        $exercises = ExerciseLibrary::whereNotNull('gif_url')->get();
        
        if ($exercises->isEmpty()) {
            // Also get exercises without gif_url to set them
            $exercises = ExerciseLibrary::all();
        }
        
        $fixed = 0;
        $notMapped = 0;
        
        foreach ($exercises as $exercise) {
            // Check if we have a mapping for this exercise
            $mappedName = $this->exerciseMapping[$exercise->name] ?? null;
            
            if ($mappedName) {
                $newUrl = $baseUrl . $mappedName . '/0.jpg';
                $exercise->gif_url = $newUrl;
                $exercise->save();
                
                $this->line("<info>✓</info> {$exercise->name} -> {$mappedName}");
                $fixed++;
            } else {
                // Try to find a partial match or use a placeholder
                $this->warn("⚠ No mapping for: {$exercise->name}");
                $notMapped++;
            }
        }
        
        $this->newLine();
        $this->info("Fixed {$fixed} exercise URLs.");
        if ($notMapped > 0) {
            $this->warn("{$notMapped} exercises without mapping.");
        }
        
        return Command::SUCCESS;
    }
}
