<?php

namespace App\Assets;

use App\Models\Asset;
use App\Services\Meta\Meta;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Process;
use Illuminate\Support\Facades\Storage;
use Throwable;

/**
 * Small copies of a creative, made once and kept.
 *
 * The panel shows creatives at 56 pixels and the generator writes 8MB JPEGs, so
 * previewing two ads pulled 16MB down the wire. Resizing once and serving the
 * copy is the difference between a panel that appears and one that hangs.
 *
 * Falls back to the original whenever anything is unusual: no GD, an
 * unsupported format, an image already smaller than the target. A slow preview
 * is better than a broken one.
 *
 * Always written to a private disk, never the one holding the source. Ids are
 * sequential, so a thumbnail on the web-served public disk would be reachable
 * at a guessable URL by anyone, which is the thing the preview route exists to
 * prevent.
 */
class Thumbnails
{
    /** Wide enough for a retina thumbnail, small enough to be instant. */
    private const WIDTH = 320;

    /** The disk thumbnails are written to. Never web served. */
    private const DISK = 'local';

    /** Retry failed frame extraction after an hour; ffmpeg can fail transiently under load. */
    private const FAILED_CACHE_SECONDS = 3600;

    /**
     * A path on the thumbnail disk, or null to serve the original.
     *
     * @return array{0: string, 1: string}|null [disk, path]
     */
    public function for(Asset $asset): ?array
    {
        // Use local video bytes before making a Graph API request for a still.
        if ($asset->kind === 'video') {
            return $this->fromLocalVideo($asset) ?? $this->fromPlatform($asset);
        }

        if ($asset->kind !== 'image' || ! function_exists('imagecreatetruecolor')) {
            return null;
        }

        $source = Storage::disk($asset->disk ?: 'local');
        $disk = Storage::disk(self::DISK);
        $target = 'thumbnails/'.$asset->id.'-'.self::WIDTH.'.jpg';

        if ($disk->exists($target)) {
            return [self::DISK, $target];
        }

        if (! $source->exists($asset->path)) {
            return null;
        }

        try {
            $image = @imagecreatefromstring($source->get($asset->path));

            if ($image === false) {
                return null;
            }

            $width = imagesx($image);
            $height = imagesy($image);

            // Already small: keep serving the original rather than writing a
            // second copy of the same thing.
            // No imagedestroy(): deprecated in PHP 8.5, which this repo runs,
            // and a no-op since 8.0 because GD images are objects now.
            if ($width <= self::WIDTH) {
                return null;
            }

            $scaled = imagescale($image, self::WIDTH, (int) round($height * self::WIDTH / $width));

            if ($scaled === false) {
                return null;
            }

            ob_start();

            try {
                imagejpeg($scaled, null, 82);
                $bytes = (string) ob_get_contents();
            } finally {
                // Closed on the way out whatever happens. A throw between
                // ob_start and ob_get_clean would otherwise leave the buffer
                // open and the encoded image would end up inside the response.
                ob_end_clean();
            }

            $disk->put($target, $bytes);

            return [self::DISK, $target];
        } catch (Throwable) {
            // A creative that will not resize still has to be viewable.
            return null;
        }
    }

    /** @return array{0: string, 1: string}|null */
    private function fromLocalVideo(Asset $asset): ?array
    {
        $sourceDiskName = $asset->disk ?: 'local';

        if (config("filesystems.disks.{$sourceDiskName}.driver") !== 'local') {
            return null;
        }

        $source = Storage::disk($sourceDiskName);
        $disk = Storage::disk(self::DISK);
        $target = 'thumbnails/'.$asset->id.'-video.jpg';

        if ($disk->exists($target)) {
            return [self::DISK, $target];
        }

        // A video ffmpeg could not read is not tried again on every render.
        $failed = 'thumbnails/'.$asset->id.'-video.failed';

        if ($disk->exists($failed)) {
            $failedAt = (int) $disk->get($failed);

            if ($failedAt > 0 && now()->timestamp - $failedAt < self::FAILED_CACHE_SECONDS) {
                return null;
            }

            $disk->delete($failed);
        }

        if (! $source->exists($asset->path) || ! $ffmpeg = $this->ffmpegBinary()) {
            return null;
        }

        $disk->makeDirectory('thumbnails');
        $temporary = 'thumbnails/'.$asset->id.'-video-'.bin2hex(random_bytes(5)).'.jpg';

        try {
            $result = Process::timeout(5)->run([
                $ffmpeg,
                '-y', '-hide_banner', '-loglevel', 'error',
                '-ss', '0.5', '-i', $source->path($asset->path),
                '-frames:v', '1', '-threads', '1',
                '-vf', 'scale=320:320:force_original_aspect_ratio=decrease',
                '-q:v', '4',
                $disk->path($temporary),
            ]);

            if (! $result->successful() || ! $disk->exists($temporary)) {
                $disk->put($failed, (string) now()->timestamp);

                return null;
            }

            if (! $disk->exists($target)) {
                $disk->move($temporary, $target);
            } else {
                $disk->delete($temporary);
            }

            return $disk->exists($target) ? [self::DISK, $target] : null;
        } catch (Throwable) {
            return null;
        } finally {
            if ($disk->exists($temporary)) {
                $disk->delete($temporary);
            }
        }
    }

    /** @var array<string, string|null> */
    private static array $ffmpegLookups = [];

    private function ffmpegBinary(): ?string
    {
        $configured = config('creative.ffmpeg_binary');
        $key = is_string($configured) ? $configured : '';

        // Memoized, absence included, so a missing ffmpeg is not searched for on every render.
        if (! array_key_exists($key, self::$ffmpegLookups)) {
            self::$ffmpegLookups[$key] = $this->locateFfmpeg($configured);
        }

        return self::$ffmpegLookups[$key];
    }

    private function locateFfmpeg(mixed $configured): ?string
    {
        $candidates = [
            is_string($configured) && $configured !== '' ? $configured : null,
            '/usr/bin/ffmpeg',
            '/usr/local/bin/ffmpeg',
            'ffmpeg',
        ];

        foreach (array_filter($candidates) as $candidate) {
            if (str_contains($candidate, '/')) {
                if (is_executable($candidate)) {
                    return $candidate;
                }

                continue;
            }

            foreach (explode(PATH_SEPARATOR, (string) getenv('PATH')) as $directory) {
                if ($directory !== '' && is_executable($directory.'/'.$candidate)) {
                    return $directory.'/'.$candidate;
                }
            }
        }

        return null;
    }

    /**
     * The still the platform made when it transcoded an uploaded video.
     *
     * Fetched once and kept, like every other thumbnail here, so the panel is
     * not making a Graph call and an image download per row on every render.
     *
     * Null until the video has actually been uploaded to an ad account; the
     * caller falls back to a local still when one can be extracted.
     *
     * @return array{0: string, 1: string}|null [disk, path]
     */
    private function fromPlatform(Asset $asset): ?array
    {
        $disk = Storage::disk(self::DISK);
        $target = 'thumbnails/'.$asset->id.'-video.jpg';

        if ($disk->exists($target)) {
            return [self::DISK, $target];
        }

        $ref = $asset->platformRefs()
            ->where('platform', 'meta')
            ->whereNotNull('external_id')
            ->first();

        if ($ref === null) {
            return null;
        }

        try {
            $uri = app(Meta::class)->videoThumbnail((string) $ref->external_id);

            if (blank($uri)) {
                return null;
            }

            // Short timeout on purpose: this runs while somebody is waiting for
            // the panel, and a missing thumbnail is a worse reason to hang than
            // it is to show a blank.
            $response = Http::timeout(5)->get($uri);

            if ($response->failed() || blank($response->body())) {
                return null;
            }

            $disk->put($target, $response->body());

            return [self::DISK, $target];
        } catch (Throwable) {
            // Same rule as the resize path: a creative we cannot preview must
            // not take the panel down with it.
            return null;
        }
    }
}
