<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Subhashladumor1\Translate\Facades\Translate;

class TranslateBuildCommand extends Command
{
    protected $signature = 'translate:build
                            {--source=fr : Langue source (fichier lang/{source}.json)}
                            {--target=en : Langue cible}
                            {--force : Écraser les traductions existantes}';

    protected $description = 'Génère lang/{target}.json en traduisant toutes les clés de lang/{source}.json via l\'API';

    public function handle(): int
    {
        $source = $this->option('source');
        $target = $this->option('target');
        $force = $this->option('force');

        $sourcePath = lang_path("{$source}.json");
        $targetPath = lang_path("{$target}.json");

        if (! File::exists($sourcePath)) {
            $this->error("Fichier source introuvable : {$sourcePath}");
            return self::FAILURE;
        }

        $sourceData = json_decode(File::get($sourcePath), true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            $this->error('Le fichier source n\'est pas un JSON valide.');
            return self::FAILURE;
        }

        $existing = [];
        if (File::exists($targetPath) && ! $force) {
            $existing = json_decode(File::get($targetPath), true) ?? [];
        }

        $toTranslate = [];
        foreach ($sourceData as $key => $value) {
            if ($force || ! isset($existing[$key])) {
                $toTranslate[$key] = $value;
            }
        }

        if (empty($toTranslate)) {
            $this->info('Aucune nouvelle traduction nécessaire.');
            return self::SUCCESS;
        }

        $this->info("Traduction de " . count($toTranslate) . " chaîne(s) : {$source} → {$target}");
        $bar = $this->output->createProgressBar(count($toTranslate));
        $bar->start();

        $translations = [];
        foreach ($toTranslate as $key => $value) {
            try {
                $translated = Translate::translate($value, $target, $source);
                $translations[$key] = $translated;
            } catch (\Throwable $e) {
                $this->newLine();
                $this->warn("  Échec pour « {$key} » : " . $e->getMessage());
                $translations[$key] = $value; // fallback sur l'original
            }
            $bar->advance();
            usleep(100_000); // 100ms entre chaque requête pour éviter le rate limiting
        }

        $bar->finish();
        $this->newLine(2);

        $result = $force ? $translations : array_merge($existing, $translations);
        ksort($result);

        File::put(
            $targetPath,
            json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
        );

        $this->info("✓ Traductions enregistrées dans {$targetPath}");
        return self::SUCCESS;
    }
}
