<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class ThumbnailJob extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();

        // Allow CLI only
        if (!is_cli()) {
            exit('CLI only');
        }

        $this->load->library('core/R2Storage');
    }

    /**
     * CLI:
     * php index.php core/jobs/ThumbnailJob generate image <r2Key>
     */
    public function generate()
    {
        if (!is_cli()) {
            exit('CLI only');
        }
        $segments = $this->uri->segment_array();

        // segment[5] = image | video
        $mediaType = $segments[5] ?? null;

        // segment[6...] = full R2 key
        $r2Key = implode('/', array_slice($segments, 5));
        //print $r2Key; exit;

        if (!$mediaType || !$r2Key) {
            echo "Invalid arguments\n";
            return;
        }
        if ($mediaType === 'image') {
            $this->generateImageThumb($r2Key);
        } elseif ($mediaType === 'video') {
            $this->generateVideoPoster($r2Key); // optional
        }

        echo "DONE\n";
    }



    /* =======================================================
     * IMAGE THUMBNAIL (single thumb)
     * ======================================================= */
    // protected function generateImageThumb(string $r2Key)
    // {
    //     $tmp = sys_get_temp_dir() . '/' . basename($r2Key);
    //     $thumbTmp = sys_get_temp_dir() . '/thumb_' . basename($r2Key);

    //     // 1️⃣ Download original
    //     $obj = $this->r2storage->get($r2Key);
    //     file_put_contents($tmp, $obj['Body']);

    //     // 2️⃣ Create image
    //     $src = imagecreatefromstring(file_get_contents($tmp));
    //     if (!$src) {
    //         unlink($tmp);
    //         return;
    //     }

    //     $w = imagesx($src);
    //     $h = imagesy($src);

    //     $thumbW = 300;
    //     $thumbH = intval($h * ($thumbW / $w));

    //     $thumb = imagecreatetruecolor($thumbW, $thumbH);
    //     imagecopyresampled($thumb, $src, 0,0,0,0, $thumbW,$thumbH,$w,$h);

    //     imagejpeg($thumb, $thumbTmp, 82);

    //     imagedestroy($src);
    //     imagedestroy($thumb);
    //     unlink($tmp);

    //     // 3️⃣ Upload thumbnail to R2
    //     $thumbKey = dirname($r2Key) . '/thumb_' . basename($r2Key);

    //     $this->r2storage->upload(
    //         $thumbKey,
    //         $thumbTmp,
    //         'image/jpeg'
    //     );

    //     unlink($thumbTmp);
    // }
    protected function generateImageThumb(string $r2Key)
    {
        $tmp      = sys_get_temp_dir() . '/' . basename($r2Key);
        $thumbTmp = sys_get_temp_dir() . '/thumb_' . basename($r2Key);

        // --------------------------------------------------
        // 1️⃣ Download original file from R2
        // --------------------------------------------------
        try {
            $obj = $this->r2storage->get($r2Key);
            $stream = $obj['Body'];
            $stream->rewind();
            file_put_contents($tmp, $stream->getContents());
        } catch (Exception $e) {
            return;
        }

        // --------------------------------------------------
        // 2️⃣ Get image info safely
        // --------------------------------------------------
        $info = @getimagesize($tmp);
        if (!$info) {
            unlink($tmp);
            return;
        }

        [$width, $height, $type] = $info;
        $pixelCount = $width * $height;

        // --------------------------------------------------
        // 3️⃣ HARD LIMIT (very important)
        // --------------------------------------------------
        // ~12 MP threshold (safe for GD & CLI)
        if ($pixelCount > 12_000_000) {
            $this->uploadDefaultLargeThumb($r2Key);
            unlink($tmp);
            return;
        }
        // --------------------------------------------------
        // 4️⃣ USE IMAGICK IF AVAILABLE (BEST)
        // --------------------------------------------------
        if (extension_loaded('imagick')) {
            try {
                $img = new Imagick($tmp);

                // HARD memory limits
                $img->setResourceLimit(Imagick::RESOURCETYPE_MEMORY, 64);
                $img->setResourceLimit(Imagick::RESOURCETYPE_MAP, 64);

                $img->thumbnailImage(300, 300, true, true);
                $img->setImageFormat('jpeg');
                $img->setImageCompressionQuality(82);
                $img->writeImage($thumbTmp);

                $img->clear();
                $img->destroy();

                $this->uploadThumb($r2Key, $thumbTmp);
                unlink($tmp);
                unlink($thumbTmp);
                return;

            } catch (Exception $e) {
                // fall through to GD
            }
        }
        // --------------------------------------------------
        // 5️⃣ SAFE GD FALLBACK
        // --------------------------------------------------
        try {
            switch ($type) {
                case IMAGETYPE_JPEG:
                    $src = imagecreatefromjpeg($tmp); break;
                case IMAGETYPE_PNG:
                    $src = imagecreatefrompng($tmp); break;
                case IMAGETYPE_WEBP:
                    $src = imagecreatefromwebp($tmp); break;
                default:
                    $this->uploadDefaultLargeThumb($r2Key);
                    unlink($tmp);
                    return;
            }

            $thumbW = 300;
            $thumbH = intval($height * ($thumbW / $width));

            $thumb = imagecreatetruecolor($thumbW, $thumbH);
            imagecopyresampled($thumb, $src, 0,0,0,0, $thumbW,$thumbH,$width,$height);
            imagejpeg($thumb, $thumbTmp, 82);

            imagedestroy($src);
            imagedestroy($thumb);

            $this->uploadThumb($r2Key, $thumbTmp);

        } catch (Exception $e) {
            $this->uploadDefaultLargeThumb($r2Key);
        }

        unlink($tmp);
        @unlink($thumbTmp);
    }
    protected function uploadThumb(string $r2Key, string $thumbTmp)
    {
        $thumbKey = dirname($r2Key) . '/thumb_' . basename($r2Key);

        $this->r2storage->upload(
            $thumbKey,
            $thumbTmp,
            'image/jpeg'
        );
    }
    protected function uploadDefaultLargeThumb(string $r2Key)
    {
        $width  = 300;
        $height = 300;

        // Create image
        $img = imagecreatetruecolor($width, $height);

        // Colors
        $bg     = imagecolorallocate($img, 245, 245, 245); // light gray
        $border = imagecolorallocate($img, 200, 200, 200);
        $text   = imagecolorallocate($img, 120, 120, 120);

        // Fill background
        imagefilledrectangle($img, 0, 0, $width, $height, $bg);

        // Draw border
        imagerectangle($img, 0, 0, $width - 1, $height - 1, $border);

        // Draw simple icon box
        imagefilledrectangle($img, 110, 80, 190, 160, $border);
        imagerectangle($img, 110, 80, 190, 160, $text);

        // Text
        imagestring($img, 5, 85, 190, 'Large Image', $text);

        // Temp file
        $tmpThumb = sys_get_temp_dir() . '/thumb_large_' . uniqid() . '.jpg';

        imagejpeg($img, $tmpThumb, 85);
        imagedestroy($img);

        // Upload to R2
        $thumbKey = dirname($r2Key) . '/thumb_' . basename($r2Key);

        $this->r2storage->upload(
            $thumbKey,
            $tmpThumb,
            'image/jpeg'
        );

        @unlink($tmpThumb);
    }
    /* =======================================================
     * VIDEO POSTER (optional)
     * ======================================================= */
    protected function generateVideoPoster(string $r2Key)
    {
        // Optional future:
        // ffmpeg -i video.mp4 -ss 00:00:01 -vframes 1 poster.jpg
    }
}
