<?php

namespace App\Service\Scraper;

use App\Entity\Chapter;
use App\Entity\ContentSource;
use Doctrine\ORM\EntityManagerInterface;
use GuzzleHttp\Client;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

class MangadexScraper extends AbstractScraper
{
    public function scrapeChapter(Chapter $chapter, ContentSource $contentSource): array|bool
    {
        $chapterUrl = $contentSource->getBaseUrl() . sprintf($contentSource->getChapterUrlFormat(), $chapter->getExternalId());
        $manga = $chapter->getManga();
        $pageData = [];

        try {
            $response = $this->httpClient->get($chapterUrl);
            $results = json_decode($response->getBody()->getContents(), true);

            if ($results['result'] !== 'ok' || count($results['chapter']['dataSaver']) === 0) {
                throw new \Exception('Error while fetching chapter data from Mangadex ' . $manga->getTitle() . ' ' . $chapter->getNumber());
            }

            $tempDir = sys_get_temp_dir() . '/' . uniqid('manga_scraper_');
            mkdir($tempDir);

            foreach ($results['chapter']['dataSaver'] as $index => $page) {
                $pageUrl = $results['baseUrl'] . '/data-saver/' . $results['chapter']['hash'] . '/' . $page;
                $imagePath = $tempDir . '/' . sprintf('%03d.%s', $index + 1, pathinfo($page, PATHINFO_EXTENSION));

                $this->downloadAndSaveImage($pageUrl, $imagePath);

                $this->dispatchProgressEvent($chapter, $index + 1, count($results['chapter']['dataSaver']));

                $pageData[] = [
                    'image_url' => $pageUrl,
                    'local_image_url' => $imagePath,
                    'page_number' => $index + 1,
                ];
            }

            $cbzFilePath = $this->generateCbzPath($manga, $chapter);
            $this->createCbzFile($pageData, $cbzFilePath);

            $chapter->setCbzPath($cbzFilePath);
            $this->entityManager->persist($chapter);
            $this->entityManager->flush();

            $this->cleanupTempFiles($tempDir);

            return $pageData;
        } catch (\Exception $e) {
            // Log the error
            return false;
        }
    }

    public function testScraping(string $mangaSlug, string $chapterNumber, ContentSource $contentSource): array
    {
        // For Mangadex, we need the chapter's external ID, which we don't have in this context.
        // We could potentially fetch it first, but for simplicity, let's return an empty array.
        return [];
    }

    public function supports(string $scrapingType): bool
    {
        return $scrapingType === 'mangadex';
    }
}
