<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Services\SkySportsService;
use App\Services\GeminiService;

class ScrapeSitemapArticles extends ScrapeSkySports
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'scrape:sitemap-articles';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Scrape latest articles for all sports categories directly from API (matches sitemap coverage)';

    /**
     * Execute the console command.
     */
    public function handle(SkySportsService $skySportsService, GeminiService $geminiService)
    {
        $this->info('Starting Category Articles Scraper...');
        
        // Use the same Categories source as the Sitemap generator
            $sport  = 'all';
            $id = '29876';
            $this->info("Scraping category: {$sport} (ID: {$id})");

            // Sitemap logic only covers Page 1, with a limit of 20 items per category
            $page = 1;
            $limit = 100;

            try {
                // Fetch the listing exactly as the Sitemap Controller logic does
                $listing = $skySportsService->getSportsCategories($sport, $id, $page, $limit);

                if (empty($listing['items'])) {
                    $this->warn("No items found for {$sport}.");
                }
                
                $count = count($listing['items']);
                $this->info("Found {$count} items. Processing...");

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

                foreach ($listing['items'] as $item) {
                    try {
                        // Reuse the processing logic from the parent class (ScrapeSkySports)
                        // Using 'false' for AI to speed up, or could expose an option
                        $this->processItem($item, $skySportsService, $geminiService, false);
                    } catch (\Exception $e) {
                         // Log::error($e->getMessage());
                    }
                    $bar->advance();
                }

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

            } catch (\Exception $e) {
                $this->error("Error extracting listing for {$sport}: " . $e->getMessage());
            }


        $this->info('Category Articles Scraping completed!');
    }
}
