<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Stichoza\GoogleTranslate\GoogleTranslate;

class TranslateJson extends Command
{
    protected $signature = 'translate:json {source=en} {targets=pl}';
    protected $description = 'Translate JSON files using free Google Translate';

    public function handle()
    {
        $source = $this->argument('source');
        $targets = explode(',', $this->argument('targets'));
        
        $sourceFile = resource_path("lang/{$source}.json");
        
        // Check if source file exists
        if (!file_exists($sourceFile)) {
            $this->error("❌ Source language file not found: {$sourceFile}");
            $this->info("💡 Create a file named '{$source}.json' in resources/lang/ with your English content");
            return;
        }

        $sourceData = json_decode(file_get_contents($sourceFile), true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            $this->error("❌ Invalid JSON in source file");
            return;
        }

        foreach ($targets as $target) {
            $this->info("🔤 Translating from {$source} to {$target}...");
            
            $translator = new GoogleTranslate($target, $source);
            $translatedData = [];
            $successCount = 0;
            $errorCount = 0;

            foreach ($sourceData as $key => $text) {
                try {
                    // Add delay to avoid being blocked
                    usleep(500000); // 0.5 second delay
                    
                    $translatedText = $translator->translate($text);
                    $translatedData[$key] = $translatedText;
                    $this->line("✅ {$text} → {$translatedText}");
                    $successCount++;
                    
                } catch (\Exception $e) {
                    $this->error("❌ Failed to translate: {$text}");
                    $this->line("   Error: " . $e->getMessage());
                    $translatedData[$key] = $text; // Keep original text
                    $errorCount++;
                }
            }
            
            $targetFile = resource_path("lang/{$target}.json");
            file_put_contents(
                $targetFile, 
                json_encode($translatedData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
            );
            
            $this->info("📁 Saved: {$targetFile}");
            $this->info("📊 Results: {$successCount} successful, {$errorCount} failed");
        }
        
        $this->info('🎉 Translation completed!');
    }
}