<?php

namespace Functional\Exercises\Console\Commands;

use Functional\Exercises\Models\Exercise;
use Illuminate\Console\Command;

/**
 * Importe les traductions d'exercices (noms fr/pt-BR + instructions pt-BR) depuis des fichiers
 * result_*.json produits hors-ligne : [{id, name_fr, name_ptBR, instr_ptBR:[...]}].
 * Met à jour exercises.name_i18n et fusionne instructions['pt-BR'].
 */
class ImportTranslationsCommand extends Command
{
    protected $signature = 'exercises:import-translations {--dir= : dossier contenant les result_*.json}';

    protected $description = 'Importe les traductions (noms fr/pt-BR + instructions pt-BR) des exercices.';

    public function handle(): int
    {
        $dir = rtrim((string) $this->option('dir'), '/');
        if (! $dir || ! is_dir($dir)) {
            $this->error("Dossier introuvable : {$dir}");

            return self::FAILURE;
        }

        $files = glob($dir . '/result_*.json');
        if (! $files) {
            $this->error('Aucun fichier result_*.json.');

            return self::FAILURE;
        }

        $updated = 0;
        $missing = 0;

        foreach ($files as $file) {
            $rows = json_decode((string) file_get_contents($file), true);
            if (! is_array($rows)) {
                $this->warn('Ignoré (JSON invalide) : ' . basename($file));

                continue;
            }

            foreach ($rows as $r) {
                $exercise = Exercise::find($r['id'] ?? null);
                if (! $exercise) {
                    $missing++;

                    continue;
                }

                $exercise->name_i18n = array_filter([
                    'fr' => $r['name_fr'] ?? null,
                    'pt-BR' => $r['name_ptBR'] ?? null,
                ]);

                if (! empty($r['instr_ptBR'])) {
                    $instructions = $exercise->instructions ?? [];
                    $instructions['pt-BR'] = array_values($r['instr_ptBR']);
                    $exercise->instructions = $instructions;
                }

                $exercise->save();
                $updated++;
            }
        }

        $this->info("Traductions importées : {$updated} exercices" . ($missing ? " ({$missing} id introuvables)" : ''));

        return self::SUCCESS;
    }
}
