<?php

namespace App\Console\Commands;

use App\Models\Article;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;

class ImportMecaprogramsArticles extends Command
{
    protected $signature = 'mecaprograms:import-articles
        {--delay=300 : Milliseconds between requests}
        {--dry-run : Print what would be imported without saving}';

    protected $description = 'Import help articles from mecaprograms.com /helpers/ pages';

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

    protected int $imported = 0;
    protected int $skipped = 0;

    protected array $articleUrls = [
        'how-to-format-pc' => 'How to Format PC?',
        'how-to-disable-a-security-boot' => 'How to Disable a Security Boot?',
        'how-to-enable-virtualization' => 'How to Enable Virtualization?',
    ];

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

        $this->newLine();
        $this->info('Processing articles...');

        foreach ($this->articleUrls as $slug => $title) {
            $this->importArticle($slug, $title);
            usleep((int) $this->option('delay') * 1000);
        }

        $this->newLine();
        $this->table(
            ['Imported', 'Skipped'],
            [[$this->imported, $this->skipped]]
        );

        return Command::SUCCESS;
    }

    protected function importArticle(string $slug, string $title): void
    {
        $this->line("  Processing: {$title}");

        $existing = Article::where('slug', $slug)->first();
        if ($existing) {
            $this->line("  Skipped (already exists): {$title}");
            $this->skipped++;
            return;
        }

        $url = "{$this->baseUrl}/helpers/{$slug}";
        $this->line("  Fetching: {$url}");

        $content = null;

        try {
            $response = Http::withOptions(['verify' => false])
                ->withHeaders(['User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'])
                ->timeout(30)
                ->get($url);

            if ($response->successful()) {
                $html = $response->body();

                if (preg_match('/<div[^>]*class="[^"]*content[^"]*"[^>]*>([\s\S]*?)<\/div>/i', $html, $m)) {
                    $content = trim(strip_tags($m[1]));
                }

                if (!$content) {
                    if (preg_match('/<article[^>]*>([\s\S]*?)<\/article>/i', $html, $m)) {
                        $content = trim(strip_tags($m[1]));
                    }
                }

                if (!$content) {
                    if (preg_match('/<main[^>]*>([\s\S]*?)<\/main>/i', $html, $m)) {
                        $content = trim(strip_tags($m[1]));
                    }
                }
            } else {
                $this->warn("  Failed (HTTP {$response->status()})");
            }
        } catch (\Exception $e) {
            $this->error("  Error fetching {$slug}: {$e->getMessage()}");
        }

        if ($this->option('dry-run')) {
            $this->line("  Would import: {$title}" . ($content ? '' : ' (no content scraped)'));
            $this->imported++;
            return;
        }

        try {
            Article::create([
                'title' => $title,
                'slug' => $slug,
                'content' => $content ? \Illuminate\Support\Str::limit($content, 5000) : "Step-by-step guide for {$title}.",
                'category' => 'Helpers',
                'order' => 0,
                'is_active' => true,
            ]);

            $this->line("  Imported: {$title}");
            $this->imported++;

        } catch (\Exception $e) {
            $this->error("  Failed to import {$title}: {$e->getMessage()}");
            $this->skipped++;
        }
    }
}
