<?php

namespace App\Console\Commands;

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

class ConvertWhoisConfigCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'whois:convert-config 
                            {--input=resources/app/whois/dist.whois.json : JSON dosya yolu}
                            {--output=config/whois.php : Çıktı dosya yolu}
                            {--backup : Eski config dosyasını yedekle}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'dist.whois.json dosyasını PHP config formatına çevirir';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $inputFile = $this->option('input');
        $outputFile = $this->option('output');
        $backup = $this->option('backup');

        $this->info(__('console.whois_converting_starting'));

        // Input dosyasını kontrol et
        if (! File::exists($inputFile)) {
            $this->error(__('console.whois_input_not_found', ['file' => $inputFile]));

            return 1;
        }

        // JSON dosyasını oku
        $this->info(__('console.whois_reading_json', ['file' => $inputFile]));
        $jsonContent = File::get($inputFile);
        $whoisData = json_decode($jsonContent, true);

        if (! $whoisData) {
            $this->error(__('console.whois_json_parse_error'));

            return 1;
        }

        $this->info(__('console.whois_json_read_success', ['count' => count($whoisData)]));

        // Eski config dosyasını yedekle
        if ($backup && File::exists($outputFile)) {
            $backupFile = $outputFile.'.backup.'.date('Y-m-d_H-i-s');
            File::copy($outputFile, $backupFile);
            $this->info(__('console.whois_backup_created', ['file' => $backupFile]));
        }

        // PHP config oluştur
        $this->info(__('console.whois_creating_php_config'));
        $phpConfig = $this->generatePhpConfig($whoisData);

        // Dosyayı yaz
        File::put($outputFile, $phpConfig);
        $this->info(__('console.whois_config_created', ['file' => $outputFile]));

        // İstatistikler
        $totalExtensions = $this->countTotalExtensions($whoisData);
        $this->info(__('console.whois_total_tlds', ['count' => count($whoisData)]));
        $this->info(__('console.whois_total_extensions', ['count' => $totalExtensions]));

        // Örnek TLD'leri göster
        $this->showSampleTlds($whoisData);

        $this->newLine();
        $this->info(__('console.whois_conversion_completed'));
        $this->info(__('console.whois_check_config'));

        return 0;
    }

    /**
     * PHP config içeriğini oluştur
     */
    protected function generatePhpConfig(array $whoisData): string
    {
        $phpConfig = "<?php\n\nreturn [\n";
        $phpConfig .= "    /*\n";
        $phpConfig .= "    |--------------------------------------------------------------------------\n";
        $phpConfig .= "    | Whois TLD Configuration\n";
        $phpConfig .= "    |--------------------------------------------------------------------------\n";
        $phpConfig .= "    |\n";
        $phpConfig .= "    | Bu dosya her TLD için whois server ve query format bilgilerini içerir.\n";
        $phpConfig .= "    | dist.whois.json dosyasından otomatik olarak oluşturulmuştur.\n";
        $phpConfig .= "    | Komut: php artisan whois:convert-config\n";
        $phpConfig .= "    |\n";
        $phpConfig .= "    */\n\n";

        $phpConfig .= "    'default_server' => 'whois.iana.org',\n";
        $phpConfig .= "    'default_timeout' => 30,\n";
        $phpConfig .= "    'default_encoding' => 'UTF-8',\n\n";

        $phpConfig .= "    'tlds' => [\n";

        // Her TLD için config oluştur
        foreach ($whoisData as $entry) {
            $extensions = explode(',', $entry['extensions']);

            foreach ($extensions as $extension) {
                $extension = trim($extension);
                if (empty($extension)) {
                    continue;
                }

                // URI'yi parse et
                $uri = $entry['uri'];
                $server = '';
                $port = '';

                if (strpos($uri, 'socket://') === 0) {
                    $server = str_replace('socket://', '', $uri);
                    if (strpos($server, ':') !== false) {
                        [$server, $port] = explode(':', $server, 2);
                    }
                } elseif (strpos($uri, 'http') === 0) {
                    $server = $uri; // HTTP URL'leri olduğu gibi bırak
                } else {
                    $server = $uri;
                }

                // Available pattern'i parse et ve escape et
                $available = $entry['available'] ?? 'No match';
                $available = str_replace("'", "\\'", $available);

                $phpConfig .= "        '{$extension}' => [\n";
                $phpConfig .= "            'server' => '{$server}',\n";
                if (! empty($port)) {
                    $phpConfig .= "            'port' => {$port},\n";
                }
                $phpConfig .= "            'query_format' => '{domain}',\n";
                $phpConfig .= "            'response_encoding' => 'UTF-8',\n";
                $phpConfig .= "            'timeout' => 30,\n";
                $phpConfig .= "            'available_pattern' => '{$available}',\n";
                if (! empty($entry['comment'])) {
                    $comment = str_replace("'", "\\'", $entry['comment']);
                    $phpConfig .= "            'comment' => '{$comment}',\n";
                }
                $phpConfig .= "        ],\n";
            }
        }

        $phpConfig .= "    ],\n\n";

        // Parsing rules ekle
        $phpConfig .= "    'parsing_rules' => [\n";
        $phpConfig .= "        'registrar' => [\n";
        $phpConfig .= "            'patterns' => [\n";
        $phpConfig .= "                '/Registrar:\\s*(.+)/i',\n";
        $phpConfig .= "                '/Registrar Name:\\s*(.+)/i',\n";
        $phpConfig .= "                '/Sponsoring Registrar:\\s*(.+)/i',\n";
        $phpConfig .= "            ],\n";
        $phpConfig .= "        ],\n";
        $phpConfig .= "        'creation_date' => [\n";
        $phpConfig .= "            'patterns' => [\n";
        $phpConfig .= "                '/Creation Date:\\s*(.+)/i',\n";
        $phpConfig .= "                '/Created:\\s*(.+)/i',\n";
        $phpConfig .= "                '/Registration Date:\\s*(.+)/i',\n";
        $phpConfig .= "            ],\n";
        $phpConfig .= "        ],\n";
        $phpConfig .= "        'expiry_date' => [\n";
        $phpConfig .= "            'patterns' => [\n";
        $phpConfig .= "                '/Registry Expiry Date:\\s*(.+)/i',\n";
        $phpConfig .= "                '/Expiration Date:\\s*(.+)/i',\n";
        $phpConfig .= "                '/Expires:\\s*(.+)/i',\n";
        $phpConfig .= "            ],\n";
        $phpConfig .= "        ],\n";
        $phpConfig .= "        'status' => [\n";
        $phpConfig .= "            'patterns' => [\n";
        $phpConfig .= "                '/Status:\\s*(.+)/i',\n";
        $phpConfig .= "                '/Domain Status:\\s*(.+)/i',\n";
        $phpConfig .= "            ],\n";
        $phpConfig .= "        ],\n";
        $phpConfig .= "        'nameservers' => [\n";
        $phpConfig .= "            'patterns' => [\n";
        $phpConfig .= "                '/Name Server:\\s*(.+)/i',\n";
        $phpConfig .= "                '/Nameservers:\\s*(.+)/i',\n";
        $phpConfig .= "            ],\n";
        $phpConfig .= "        ],\n";
        $phpConfig .= "    ],\n\n";

        // Cache ayarları
        $phpConfig .= "    'cache' => [\n";
        $phpConfig .= "        'enabled' => true,\n";
        $phpConfig .= "        'ttl' => 3600, // 1 saat\n";
        $phpConfig .= "        'prefix' => 'whois_query_',\n";
        $phpConfig .= "    ],\n";

        $phpConfig .= "];\n";

        return $phpConfig;
    }

    /**
     * Toplam extension sayısını hesapla
     */
    protected function countTotalExtensions(array $whoisData): int
    {
        $total = 0;
        foreach ($whoisData as $entry) {
            $extensions = explode(',', $entry['extensions']);
            $total += count($extensions);
        }

        return $total;
    }

    /**
     * Örnek TLD'leri göster
     */
    protected function showSampleTlds(array $whoisData): void
    {
        $this->newLine();
        $this->info(__('console.whois_sample_tlds'));

        $sampleCount = 0;
        foreach ($whoisData as $entry) {
            if ($sampleCount >= 5) {
                break;
            }

            $extensions = explode(',', $entry['extensions']);
            $firstExt = trim($extensions[0]);
            $server = str_replace('socket://', '', $entry['uri']);

            $this->line("   • {$firstExt} → {$server}");
            $sampleCount++;
        }

        if (count($whoisData) > 5) {
            $this->line(__('console.whois_and_more_tlds', ['count' => count($whoisData) - 5]));
        }
    }
}
