<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Http;
use Intervention\Image\ImageManager;
use Intervention\Image\Drivers\Gd\Driver;
use Illuminate\Support\Str;

class AutoFillCategoryImages extends Command
{
    protected $signature = 'categories:auto-images 
                            {--force : Re-download all images even if exists}
                            {--source=auto : Image source: auto, clearbit, placeholder}';
    
    protected $description = 'Automatically download/generate images for categories without images';

    private $stats = ['downloaded' => 0, 'generated' => 0, 'failed' => 0, 'skipped' => 0];

    public function handle()
    {
        $this->info('🎨 Auto-filling category images...');
        $this->newLine();

        $force = $this->option('force');
        $source = $this->option('source');

        // Get categories without images
        $query = DB::table('categories');
        
        if (!$force) {
            $query->where(function($q) {
                $q->whereNull('image')
                  ->orWhere('image', '');
            });
        }

        $categories = $query->get();

        if ($categories->isEmpty()) {
            $this->info('✅ All categories already have images!');
            return 0;
        }

        $this->info("Found {$categories->count()} categories without images");
        $this->newLine();

        $bar = $this->output->createProgressBar($categories->count());
        $bar->start();

        foreach ($categories as $category) {
            $this->processCategory($category, $source);
            $bar->advance();
        }

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

        // Summary
        $this->info('📊 Summary:');
        $this->line("  ✅ Downloaded: {$this->stats['downloaded']}");
        $this->line("  🎨 Generated: {$this->stats['generated']}");
        $this->line("  ❌ Failed: {$this->stats['failed']}");
        $this->line("  ⏭️  Skipped: {$this->stats['skipped']}");

        return 0;
    }

    private function processCategory($category, $source)
    {
        $name = $category->name;
        
        // Try different sources based on priority
        $image = null;

        if ($source === 'auto' || $source === 'clearbit') {
            $image = $this->tryDownloadFromClearbit($name);
        }

        if (!$image && ($source === 'auto' || $source === 'logo-api')) {
            $image = $this->tryDownloadFromLogoAPI($name);
        }

        if (!$image && ($source === 'auto' || $source === 'placeholder')) {
            $image = $this->generatePlaceholder($name, $category->category_type);
        }

        if ($image) {
            // Save to database
            DB::table('categories')->where('id', $category->id)->update([
                'image' => $image,
                'manual_image' => true,  // Mark as manual to protect from sync
                'updated_at' => now()
            ]);
        } else {
            $this->stats['failed']++;
        }
    }

    /**
     * Try download from Clearbit Logo API
     */
    private function tryDownloadFromClearbit($name)
    {
        try {
            // Map common brands to domains
            $domain = $this->guessDomain($name);
            
            if (!$domain) {
                return null;
            }

            $url = "https://logo.clearbit.com/{$domain}";
            
            $response = Http::timeout(10)->get($url);
            
            if ($response->successful() && $response->header('Content-Type') && str_contains($response->header('Content-Type'), 'image')) {
                $fileName = 'cat-' . Str::slug($name) . '-' . time() . '.webp';
                $path = 'categories/' . $fileName;
                
                // Convert to WebP
                $manager = new ImageManager(new Driver());
                $image = $manager->read($response->body());
                $image->scale(width: 400);
                $image->toWebp(75)->save(storage_path('app/public/' . $path));
                
                $this->stats['downloaded']++;
                return $path;
            }
        } catch (\Exception $e) {
            // Silent fail, try next source
        }

        return null;
    }

    /**
     * Try download from Logo.dev API (alternative)
     */
    private function tryDownloadFromLogoAPI($name)
    {
        try {
            $domain = $this->guessDomain($name);
            
            if (!$domain) {
                return null;
            }

            // Alternative: logo.dev
            $url = "https://img.logo.dev/{$domain}?token=pk_X-LnhVKGSN2dXDKS0GJhKQ&size=200";
            
            $response = Http::timeout(10)->get($url);
            
            if ($response->successful()) {
                $fileName = 'cat-' . Str::slug($name) . '-' . time() . '.webp';
                $path = 'categories/' . $fileName;
                
                $manager = new ImageManager(new Driver());
                $image = $manager->read($response->body());
                $image->scale(width: 400);
                $image->toWebp(75)->save(storage_path('app/public/' . $path));
                
                $this->stats['downloaded']++;
                return $path;
            }
        } catch (\Exception $e) {
            // Silent fail
        }

        return null;
    }

    /**
     * Generate colorful placeholder with brand initial
     */
    private function generatePlaceholder($name, $type)
    {
        try {
            $fileName = 'cat-' . Str::slug($name) . '-' . time() . '.webp';
            $path = 'categories/' . $fileName;
            
            // Get initial
            $initial = strtoupper(mb_substr($name, 0, 2));
            
            // Color based on category type
            $colors = [
                'game' => '#667eea',
                'ewallet' => '#f093fb',
                'pulsa' => '#4facfe',
                'streaming' => '#fa709a',
                'subscription' => '#30cfd0',
                'voucher' => '#a8edea',
                'pln' => '#feca57',
            ];
            
            $bgColor = $colors[$type] ?? '#667eea';
            
            // Create simple SVG
            $svg = <<<SVG
<svg width="400" height="400" xmlns="http://www.w3.org/2000/svg">
  <rect width="400" height="400" fill="{$bgColor}"/>
  <text x="50%" y="50%" font-size="120" font-family="Arial, sans-serif" 
        fill="white" text-anchor="middle" dominant-baseline="middle" 
        font-weight="bold">{$initial}</text>
</svg>
SVG;

            // Convert SVG to image
            $manager = new ImageManager(new Driver());
            $image = $manager->read($svg);
            $image->scale(width: 400);
            $image->toWebp(75)->save(storage_path('app/public/' . $path));
            
            $this->stats['generated']++;
            return $path;
            
        } catch (\Exception $e) {
            // Fallback: create solid color square
            try {
                $manager = new ImageManager(new Driver());
                $image = $manager->create(400, 400);
                
                $colors = [
                    'game' => [102, 126, 234],
                    'ewallet' => [240, 147, 251],
                    'pulsa' => [79, 172, 254],
                    'streaming' => [250, 112, 154],
                    'subscription' => [48, 207, 208],
                    'voucher' => [168, 237, 234],
                    'pln' => [254, 202, 87],
                ];
                
                $rgb = $colors[$type] ?? [102, 126, 234];
                
                $image->drawRectangle(0, 0, function ($rectangle) use ($rgb) {
                    $rectangle->size(400, 400);
                    $rectangle->background("rgb({$rgb[0]}, {$rgb[1]}, {$rgb[2]})");
                });
                
                $image->toWebp(75)->save(storage_path('app/public/' . $path));
                
                $this->stats['generated']++;
                return $path;
                
            } catch (\Exception $e2) {
                $this->warn("  Failed to generate placeholder for {$name}: " . $e2->getMessage());
                return null;
            }
        }
    }

    /**
     * Guess domain from brand name
     */
    private function guessDomain($name)
    {
        $name = strtolower($name);
        
        // Manual mapping for known brands
        $mapping = [
            // E-Wallets
            'dana' => 'dana.id',
            'ovo' => 'ovo.id',
            'gopay' => 'gojek.com',
            'linkaja' => 'linkaja.id',
            'shopeepay' => 'shopee.co.id',
            'bri brizzi' => 'bri.co.id',
            'brizzi' => 'bri.co.id',
            'mandiri e-toll' => 'bankmandiri.co.id',
            
            // Telco
            'telkomsel' => 'telkomsel.com',
            'indosat' => 'indosat.com',
            'xl' => 'xl.co.id',
            'axis' => 'axis.co.id',
            'tri' => 'tri.co.id',
            'smartfren' => 'smartfren.com',
            'by.u' => 'byu.id',
            
            // Streaming
            'netflix' => 'netflix.com',
            'spotify' => 'spotify.com',
            'youtube' => 'youtube.com',
            'disney' => 'disneyplus.com',
            'vidio' => 'vidio.com',
            'viu' => 'viu.com',
            'iqiyi' => 'iqiyi.com',
            'wetv' => 'wetv.vip',
            'amazon prime' => 'primevideo.com',
            'bstation' => 'bilibili.tv',
            
            // Subscription Apps
            'canva' => 'canva.com',
            'capcut' => 'capcut.com',
            'alight motion' => 'alight.link',
            'perplexity' => 'perplexity.ai',
            'chatgpt' => 'openai.com',
            'gemini' => 'gemini.google.com',
            
            // Games
            'mobile legends' => 'mobilelegends.com',
            'pubg' => 'pubgmobile.com',
            'free fire' => 'ff.garena.com',
            'genshin' => 'genshin.hoyoverse.com',
            'valorant' => 'playvalorant.com',
            'lords mobile' => 'lordsmobile.com',
            
            // Vouchers
            'steam' => 'steampowered.com',
            'razer' => 'razer.com',
            'grab' => 'grab.com',
            'shopee' => 'shopee.co.id',
            'tokopedia' => 'tokopedia.com',
            'alfamart' => 'alfamartku.com',
            'indomaret' => 'indomaret.co.id',
            
            // PLN
            'pln' => 'pln.co.id',
        ];

        foreach ($mapping as $key => $domain) {
            if (str_contains($name, $key)) {
                return $domain;
            }
        }

        return null;
    }
}