<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Klevze\ControlPanel\Facades\FileManager;
use Klevze\ControlPanel\Core\Utils\Translation as TranslationUtil;

class ExportMissingTranslations extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'translations:export-missing {file=admin} {--out=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Export missing translations for a file (e.g. admin) into a CSV';

    private $translationURL = "https://cPad.dev/api/translation/get/list";
    private $token = 'Ddt06xvjYX1TK792H4jAtld8UhgVORYIpkB7nBX6';

    public function handle(): int
    {
        $type = $this->argument('file') ?? 'admin';
        $this->info('Exporting missing translations for: ' . $type);

        // Gather files to scan
        $files = [];
        $files = array_merge(
            FileManager::getFileList(app_path(), true),
            FileManager::getFileList(base_path('packages'), true),
            FileManager::getFileList(resource_path(), true)
        );

        $tempTranslations = [];

        foreach ($files as $file) {
            $res = TranslationUtil::findTranslations($file, $type);
            if (!empty($res) && is_array($res)) {
                $tempTranslations[] = $res;
            }
        }

        $tempTranslations = collect($tempTranslations)->collapse();

        $missing = [];
        foreach ($tempTranslations as $keycode => $row) {
            $exists = DB::table('translations')->where('keycode', $keycode)->where('file', $type)->exists();
            if (! $exists) {
                $missing[] = $keycode;
            }
        }

        $this->info('Found ' . count($missing) . ' missing keys');

        // Fetch suggested translations from external service for sl and en
        $suggestions = [];
        if (!empty($missing)) {
            $payload = [
                'keys' => $missing,
                'languages' => ['sl', 'en'],
            ];

            try {
                $resp = Http::withToken($this->token)->post($this->translationURL, $payload);
                if ($resp->successful()) {
                    $suggestions = $resp->json();
                } else {
                    $this->warn('Translation suggestion service returned ' . $resp->status());
                }
            } catch (\Throwable $e) {
                $this->warn('Failed to call suggestion service: ' . $e->getMessage());
            }
        }

        // Build CSV
        $out = $this->option('out') ?: storage_path('app/translations_missing_' . $type . '.csv');
        $fh = fopen($out, 'w');
        if (! $fh) {
            $this->error('Failed to open output file: ' . $out);
            return 1;
        }

        // Header
        fputcsv($fh, ['file','keycode','suggested_sl','suggested_en','placeholder']);

        foreach ($missing as $key) {
            $s_sl = $suggestions[$key]['sl'] ?? '';
            $s_en = $suggestions[$key]['en'] ?? '';
            $placeholder = $type . '.' . $key;
            fputcsv($fh, [$type, $key, $s_sl, $s_en, $placeholder]);
        }

        fclose($fh);

        $this->info('CSV exported to: ' . $out);

        return 0;
    }
}
