<?php

namespace App\Console\Commands;

use App\Models\WhatsAppPlugin;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;

class ImportMecaprogramsWhatsAppPlugins extends Command
{
    protected $signature = 'mecaprograms:import-whatsapp-plugins
        {--dry-run : Print what would be installed without saving}';

    protected $description = 'Install WhatsApp chat plugins detected on mecaprograms.com';

    protected string $baseUrl = 'https://mecaprograms.com';

    protected array $pluginMap = [
        'whatsapp' => [
            'class' => \App\WhatsAppPlugins\WhatsAppGateway::class,
            'keywords' => ['whatsapp', 'wa.link'],
        ],
        'messenger' => [
            'class' => \App\WhatsAppPlugins\MessengerPlugin::class,
            'keywords' => ['messenger', 'm.me'],
        ],
        'telegram' => [
            'class' => \App\WhatsAppPlugins\TelegramPlugin::class,
            'keywords' => ['telegram', 't.me'],
        ],
        'skype' => [
            'class' => \App\WhatsAppPlugins\SkypePlugin::class,
            'keywords' => ['skype'],
        ],
        'wechat' => [
            'class' => \App\WhatsAppPlugins\WeChatPlugin::class,
            'keywords' => ['wechat', 'u.wechat.com'],
        ],
    ];

    protected int $installed = 0;
    protected int $skipped = 0;

    public function handle(): int
    {
        ini_set('memory_limit', '512M');
        $this->info('Fetching mecaprograms.com homepage...');

        $html = $this->fetchHomepage();
        if (!$html) {
            return Command::FAILURE;
        }

        $detected = $this->detectPlugins($html);
        $this->info('Detected ' . count($detected) . ' chat channel(s)');

        if (empty($detected)) {
            $this->warn('No chat channels detected on homepage.');
            return Command::SUCCESS;
        }

        $this->newLine();
        $this->info('Installing chat plugins...');

        $whatsappData = $this->extractWhatsAppData($html);

        $toInstall = $this->resolvePlugins($detected);

        foreach ($toInstall as $code => &$plugin) {
            $defaultConfig = $this->getDefaultConfig($code, $whatsappData);
            $this->installPlugin($code, $plugin, $defaultConfig);
        }
        unset($plugin);

        $this->newLine();
        $this->table(
            ['Plugin', 'Status'],
            array_map(fn($p) => [$p['name'], $p['status']], $toInstall)
        );

        $this->newLine();
        $this->info("Installed: {$this->installed}, Skipped: {$this->skipped}");

        return Command::SUCCESS;
    }

    protected function fetchHomepage(): ?string
    {
        $response = Http::withOptions(['verify' => false])
            ->withHeaders(['User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'])
            ->timeout(30)
            ->get($this->baseUrl);

        if (!$response->successful()) {
            $this->error("Failed to fetch homepage (HTTP {$response->status()})");
            return null;
        }

        return $response->body();
    }

    protected function detectPlugins(string $html): array
    {
        $detected = [];
        $lower = strtolower($html);

        foreach ($this->pluginMap as $code => $plugin) {
            foreach ($plugin['keywords'] as $keyword) {
                if (str_contains($lower, $keyword)) {
                    $detected[$code] = true;
                    break;
                }
            }
        }

        return array_keys($detected);
    }

    protected function extractWhatsAppData(string $html): array
    {
        $data = [];

        preg_match('/"whatsapp"\s*:\s*"([^"]+)"/', $html, $urlMatch);
        if (!empty($urlMatch[1])) {
            $url = stripcslashes($urlMatch[1]);
            $data['whatsapp_url'] = $url;

            preg_match('/phone=(\d+)', $url, $phoneMatch);
            if (!empty($phoneMatch[1])) {
                $data['whatsapp_number_raw'] = $phoneMatch[1];
                $data['whatsapp_number'] = $this->formatPhone($phoneMatch[1]);
            }
        }

        preg_match('/"number_formatted"\s*:\s*"([^"]+)"/', $html, $displayMatch);
        if (!empty($displayMatch[1]) && empty($data['whatsapp_number'])) {
            $data['whatsapp_number'] = stripcslashes($displayMatch[1]);
        }

        preg_match('/"messenger"\s*:\s*"([^"]+)"/', $html, $mMatch);
        if (!empty($mMatch[1])) {
            $data['messenger_url'] = stripcslashes($mMatch[1]);
        }

        preg_match('/"telegram"\s*:\s*"([^"]+)"/', $html, $tMatch);
        if (!empty($tMatch[1])) {
            $data['telegram_url'] = stripcslashes($tMatch[1]);
        }

        preg_match('/"skype"\s*:\s*"([^"]+)"/', $html, $sMatch);
        if (!empty($sMatch[1])) {
            $data['skype_url'] = stripcslashes($sMatch[1]);
        }

        preg_match('/"wechat"\s*:\s*"([^"]+)"/', $html, $wMatch);
        if (!empty($wMatch[1])) {
            $data['wechat_url'] = stripcslashes($wMatch[1]);
        }

        return $data;
    }

    protected function formatPhone(string $phone): string
    {
        if (strlen($phone) === 12 && str_starts_with($phone, '57')) {
            return '+' . substr($phone, 0, 2) . ' ' . substr($phone, 2, 3) . ' ' . substr($phone, 5);
        }
        if (strlen($phone) === 11 && str_starts_with($phone, '51')) {
            return '+' . substr($phone, 0, 2) . ' ' . substr($phone, 2, 3) . ' ' . substr($phone, 5);
        }
        return '+' . $phone;
    }

    protected function resolvePlugins(array $codes): array
    {
        $result = [];
        $maxOrder = WhatsAppPlugin::max('order') ?? 0;
        $order = $maxOrder + 1;

        foreach ($codes as $code) {
            if (!isset($this->pluginMap[$code])) continue;

            $existing = WhatsAppPlugin::where('code', $code)->first();

            $result[$code] = [
                'name' => app($this->pluginMap[$code]['class'])->getName(),
                'code' => $code,
                'class' => $this->pluginMap[$code]['class'],
                'order' => $order++,
                'existing' => $existing,
                'status' => 'pending',
            ];
        }

        if (!isset($result['whatsapp']) && app(\App\WhatsAppPlugins\WhatsAppGateway::class)) {
            $result = array_merge(
                ['whatsapp' => [
                    'name' => 'WhatsApp',
                    'code' => 'whatsapp',
                    'class' => $this->pluginMap['whatsapp']['class'],
                    'order' => $order++,
                    'existing' => WhatsAppPlugin::where('code', 'whatsapp')->first(),
                    'status' => 'pending',
                ]],
                $result
            );
        }

        return $result;
    }

    protected function getDefaultConfig(string $code, array $data): array
    {
        return match ($code) {
            'whatsapp' => [
                'number' => $data['whatsapp_number'] ?? '+57 300 9134148',
                'number_raw' => $data['whatsapp_number_raw'] ?? '573009134148',
                'default_message' => 'Hello I come from the web, I am interested',
                'url' => $data['whatsapp_url'] ?? 'https://api.whatsapp.com/send?phone=573009134148&text=Hello%20I%20come%20from%20the%20web%2C%20I%20am%20interested',
            ],
            'messenger' => [
                'page_id' => 'mecaprograms1',
                'url' => $data['messenger_url'] ?? 'https://m.me/mecaprograms1',
            ],
            'telegram' => [
                'username' => 'Mecaprograms',
                'url' => $data['telegram_url'] ?? 'https://t.me/Mecaprograms',
            ],
            'skype' => [
                'skype_id' => 'https://join.skype.com/invite/or28j5E44Zv4',
                'url' => $data['skype_url'] ?? 'https://join.skype.com/invite/or28j5E44Zv4',
            ],
            'wechat' => [
                'wechat_id' => 'https://msng.link/o?https%3A%2F%2Fu.wechat.com%2FkM1Yy8HspAiANWcWHqO7hVM=wc',
                'url' => $data['wechat_url'] ?? 'https://msng.link/o?https%3A%2F%2Fu.wechat.com%2FkM1Yy8HspAiANWcWHqO7hVM=wc',
            ],
            default => [],
        };
    }

    protected function installPlugin(string $code, array &$plugin, array $defaultConfig): void
    {
        if ($plugin['existing']) {
            $gw = $plugin['existing'];
            if (!$gw->is_installed) {
                $gw->update(['is_installed' => true, 'config' => $defaultConfig]);
                $this->line("  Installed: {$plugin['name']}");
                $this->installed++;
                $plugin['status'] = '<fg=green>Installed</>';
            } else {
                $this->line("  Skipped (already installed): {$plugin['name']}");
                $this->skipped++;
                $plugin['status'] = '<fg=yellow>Already Installed</>';
            }
            return;
        }

        $instance = app($plugin['class']);

        if ($this->option('dry-run')) {
            $this->line("  Would install: {$plugin['name']}");
            $this->installed++;
            $plugin['status'] = '<fg=yellow>Dry Run</>';
            return;
        }

        try {
            WhatsAppPlugin::create([
                'code' => $code,
                'name' => $instance->getName(),
                'description' => $instance->getDescription(),
                'version' => $instance->getVersion(),
                'author' => $instance->getAuthor(),
                'icon' => $instance->getIcon(),
                'is_installed' => true,
                'is_active' => true,
                'config' => $defaultConfig,
                'order' => $plugin['order'],
            ]);

            $this->line("  Installed: {$plugin['name']}");
            $this->installed++;
            $plugin['status'] = '<fg=green>Installed</>';

        } catch (\Exception $e) {
            $this->error("  Failed to install {$plugin['name']}: {$e->getMessage()}");
            $plugin['status'] = '<fg=red>Failed</>';
        }
    }
}
