<?php

declare(strict_types=1);

namespace App\Domain\Shared\Infrastructure\Service;

use App\Domain\Shared\Domain\Contract\FileUploadInterface;
use App\Domain\Shared\Domain\Contract\MangaPathManagerInterface;

/**
 * Implémentation centralisée basée sur la logique éprouvée de CbzGenerator.
 */
readonly class MangaFileManager implements MangaPathManagerInterface
{
    public function __construct(
        private string $projectDir,
        private FileUploadInterface $fileUpload,
    ) {
    }

    public function getMangaDirectory(string $mangaTitle, string $publicationYear): string
    {
        $mangaDirName = ucfirst($this->slugify($mangaTitle)) . ' (' . $publicationYear . ')';
        $dir = sprintf('%s/public/cbz/%s', $this->projectDir, $mangaDirName);
        $this->ensureDirectory($dir);
        return $dir;
    }

    public function getVolumeDirectory(string $mangaTitle, string $publicationYear, int $volumeNumber): string
    {
        $mangaDir = $this->getMangaDirectory($mangaTitle, $publicationYear);
        $dir = sprintf('%s/volume_%02d', $mangaDir, $volumeNumber);
        $this->ensureDirectory($dir);
        return $dir;
    }

    public function buildChapterCbzPath(string $mangaTitle, string $publicationYear, int $volumeNumber, string $chapterNumber): string
    {
        $volumeDir = $this->getVolumeDirectory($mangaTitle, $publicationYear, $volumeNumber);
        return sprintf(
            '%s/%s_vol%d_ch%s.cbz',
            $volumeDir,
            $this->slugify($mangaTitle),
            $volumeNumber,
            $chapterNumber,
        );
    }

    public function buildVolumeCbzPath(string $mangaTitle, string $publicationYear, int $volumeNumber): string
    {
        $volumeDir = $this->getVolumeDirectory($mangaTitle, $publicationYear, $volumeNumber);
        return sprintf(
            '%s/%s_vol%d.cbz',
            $volumeDir,
            $this->slugify($mangaTitle),
            $volumeNumber,
        );
    }

    /** @param array<int, string> $files */
    public function createCbzArchive(array $files, string $cbzPath): void
    {
        $zip = new \ZipArchive();
        if ($zip->open($cbzPath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) !== true) {
            throw new \RuntimeException('Failed to create CBZ archive');
        }

        foreach ($files as $file) {
            if (!file_exists($file)) {
                throw new \RuntimeException("File not found: $file");
            }
            $zip->addFile($file, basename($file));
        }

        if (!$zip->close()) {
            throw new \RuntimeException('Failed to close CBZ archive');
        }
    }

    public function moveFileTo(string $sourcePath, string $destinationPath): void
    {
        $destinationDir = dirname($destinationPath);
        $this->ensureDirectory($destinationDir);
        $this->fileUpload->moveFile($sourcePath, $destinationPath);
    }

    public function fileExists(string $path): bool
    {
        return $this->fileUpload->fileExists($path);
    }

    private function ensureDirectory(string $dir): void
    {
        if (!is_dir($dir)) {
            $this->fileUpload->createDirectory($dir);
        }
    }

    private function slugify(string $text): string
    {
        $text = preg_replace('~[^\pL\d]+~u', '-', $text);
        $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
        $text = preg_replace('~[^-\w]+~', '', $text);
        $text = trim($text, '-');
        $text = preg_replace('~-+~', '-', $text);
        $text = strtolower($text);
        return $text ?: 'n-a';
    }
}
