<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Services\GeminiService;
use App\Models\Post;
use App\Models\Category;
use Illuminate\Support\Str;

class GenerateArticle extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'generate:article {topic : The topic to write about} {--category=general : The slug of the category}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate an SEO-friendly article using Gemini AI';

    /**
     * Execute the console command.
     */
    public function handle(GeminiService $geminiService, \App\Services\ImageScraperService $imageScraper)
    {
        $topic = $this->argument('topic');
        $categorySlug = $this->option('category');

        $this->info("Generating article about: {$topic}...");

        $articleData = $geminiService->generateArticle($topic);

        if (empty($articleData['title']) || empty($articleData['content'])) {
            $this->error('Failed to generate content.');
            return;
        }
        
        // Try scraping an image if the user requested it (feature added)
        $scrapedImage = $imageScraper->scrapeYandexImage($topic);
        if ($scrapedImage) {
            $this->info("Found image via Scraper: " . $scrapedImage);
            $articleData['image'] = $scrapedImage;
        }

        // Find or create category
        $category = Category::firstOrCreate(
            ['slug' => Str::slug($categorySlug)],
            ['name' => ucwords(str_replace('-', ' ', $categorySlug))]
        );

        // Save Post
        $post = Post::create([
            'title' => $articleData['title'],
            'slug' => Str::slug($articleData['title']) . '-' . rand(1000, 9999), // Ensure uniqueness
            'content' => $articleData['content'],
            'excerpt' => $articleData['excerpt'] ?? Str::limit(strip_tags($articleData['content']), 150),
            'image' => $articleData['image'] ?? null,
            'category_id' => $category->id,
            'tags' => $articleData['tags'] ?? 'ai-generated',
            'is_published' => true,
            'published_at' => now(),
            'meta_title' => $articleData['title'],
            'meta_description' => $articleData['excerpt'] ?? '',
            'meta_keywords' => $articleData['meta_keywords'] ?? '',
        ]);

        $this->info("Article created successfully: {$post->title}");
        $this->line("URL: " . url("/post/{$post->slug}"));
    }
}
