<?php

namespace Functional\Exercises\Console\Commands;

use Functional\Exercises\Models\Exercise;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

/**
 * Importe le dataset d'exercices (fork hasaneyldrm/exercises-dataset).
 * JSON : upsert par external_id. --media : pousse aussi images+gifs vers RustFS/S3.
 */
class ImportExercisesCommand extends Command
{
    protected $signature = 'exercises:import
        {--path= : racine du dataset (contient data/exercises.json, images/, videos/)}
        {--media : uploade aussi les images/gifs vers le disque S3 "media"}
        {--langs=en,fr : langues d instructions à conserver (pt-BR retombe sur en)}
        {--fresh : vide la table avant import}';

    protected $description = "Importe le dataset d'exercices (JSON) et, avec --media, les médias vers RustFS/S3.";

    public function handle(): int
    {
        $root = rtrim($this->option('path') ?: storage_path('app/dataset'), '/');
        $json = is_file("$root/data/exercises.json") ? "$root/data/exercises.json" : "$root/exercises.json";

        if (! is_file($json)) {
            $this->error("exercises.json introuvable sous {$root}");

            return self::FAILURE;
        }

        $langs = array_values(array_filter(array_map('trim', explode(',', (string) $this->option('langs')))));
        $records = json_decode((string) file_get_contents($json), true);

        if (! is_array($records)) {
            $this->error('JSON invalide');

            return self::FAILURE;
        }

        if ($this->option('fresh')) {
            Exercise::query()->delete();
            $this->warn('Table exercises vidée.');
        }

        $media = (bool) $this->option('media');
        $prefix = trim((string) config('exercises.media_prefix', 'exercises'), '/');
        $disk = $media ? Storage::disk('media') : null;

        $bar = $this->output->createProgressBar(count($records));
        $bar->start();
        $imported = 0;
        $uploaded = 0;

        foreach ($records as $r) {
            $ext = (string) ($r['id'] ?? '');
            if ($ext === '') {
                $bar->advance();

                continue;
            }

            // Instructions : on garde les étapes (arrays) des langues demandées.
            $steps = $r['instruction_steps'] ?? [];
            $instructions = [];
            foreach ($langs as $l) {
                if (! empty($steps[$l])) {
                    $instructions[$l] = array_values($steps[$l]);
                }
            }

            $imgKey = ! empty($r['image']) ? "{$prefix}/{$ext}.jpg" : null;
            $gifKey = ! empty($r['gif_url']) ? "{$prefix}/{$ext}.gif" : null;

            if ($media && $disk) {
                foreach ([[$r['image'] ?? null, $imgKey], [$r['gif_url'] ?? null, $gifKey]] as [$rel, $key]) {
                    if ($rel && $key && is_file("{$root}/{$rel}") && ! $disk->exists($key)) {
                        $disk->put($key, (string) file_get_contents("{$root}/{$rel}"), 'public');
                        $uploaded++;
                    }
                }
            }

            Exercise::updateOrCreate(
                ['external_id' => $ext],
                [
                    'name' => $r['name'] ?? $ext,
                    'slug' => Str::slug(($r['name'] ?? $ext) . '-' . $ext),
                    'category' => $r['category'] ?? null,
                    'body_part' => $r['body_part'] ?? null,
                    'equipment' => $r['equipment'] ?? null,
                    'target' => $r['target'] ?? null,
                    'muscle_group' => $r['muscle_group'] ?? null,
                    'secondary_muscles' => $r['secondary_muscles'] ?? [],
                    'instructions' => $instructions,
                    'image_path' => $imgKey,
                    'gif_path' => $gifKey,
                    'attribution' => $r['attribution'] ?? null,
                ]
            );

            $imported++;
            $bar->advance();
        }

        $bar->finish();
        $this->newLine();
        $this->info("Importé/à jour : {$imported} exercices" . ($media ? " (+ {$uploaded} médias S3)" : ''));

        return self::SUCCESS;
    }
}
