<?php

namespace App\Console\Commands;

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

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

    protected $description = 'Import video plugin configurations from mecaprograms.com';

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

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

        $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 Command::FAILURE;
        }

        $html = $response->body();
        $plugins = [];

        // Extract YouTube channel URL from footer social links
        if (preg_match('/"youtube":"([^"]+)"/', $html, $m)) {
            $plugins['youtube'] = [
                'channel_url' => str_replace('\/', '/', $m[1]),
            ];
            $this->line("  Found YouTube channel: {$plugins['youtube']['channel_url']}");
        } elseif (preg_match('/youtube\.com\/@[a-zA-Z0-9._-]+/', $html, $m)) {
            $plugins['youtube'] = [
                'channel_url' => 'https://www.' . $m[0],
            ];
            $this->line("  Found YouTube channel: {$plugins['youtube']['channel_url']}");
        }

        if ($this->option('dry-run')) {
            $this->info('Dry run complete. Nothing was saved.');
            return Command::SUCCESS;
        }

        foreach ($plugins as $code => $config) {
            $existing = VideoPlugin::where('code', $code)->first();
            if ($existing) {
                $existing->update([
                    'config' => $config + ($existing->config ?? []),
                    'is_installed' => true,
                ]);
                $this->line("  Updated: {$existing->name}");
            } else {
                $pluginConfig = config("video_plugins.{$code}");
                if (!$pluginConfig || !class_exists($pluginConfig['class'])) {
                    $this->warn("    Plugin class for '{$code}' not found. Skipping.");
                    continue;
                }

                $plugin = app($pluginConfig['class']);
                VideoPlugin::create([
                    'code' => $code,
                    'name' => $pluginConfig['name'],
                    'description' => $pluginConfig['description'],
                    'version' => $plugin->getVersion(),
                    'author' => $plugin->getAuthor(),
                    'is_active' => false,
                    'is_installed' => true,
                    'config' => $config,
                    'order' => VideoPlugin::max('order') + 1,
                ]);
                $this->line("  Created: {$pluginConfig['name']}");
            }
        }

        // Install plugins not detected on site
        $detectedCodes = array_keys($plugins);
        foreach (config('video_plugins', []) as $code => $pluginConfig) {
            if (in_array($code, $detectedCodes)) continue;

            $existing = VideoPlugin::where('code', $code)->first();
            if (!$existing) {
                if (!class_exists($pluginConfig['class'])) continue;
                $plugin = app($pluginConfig['class']);
                VideoPlugin::create([
                    'code' => $code,
                    'name' => $pluginConfig['name'],
                    'description' => $pluginConfig['description'],
                    'version' => $plugin->getVersion(),
                    'author' => $plugin->getAuthor(),
                    'is_active' => false,
                    'is_installed' => true,
                    'config' => [],
                    'order' => VideoPlugin::max('order') + 1,
                ]);
                $this->line("  Created (no site data): {$pluginConfig['name']}");
            }
        }

        $this->info('Video Plugins imported successfully.');

        return Command::SUCCESS;
    }
}
