<?php

namespace App\Jobs\Tasks;

use App\Helpers\FirstParty\OSSUploader\OSSUploader;
use App\Models\AiTool;
use App\Models\UrlToCrawl;
use Exception;
use Image;
use Spatie\Browsershot\Browsershot;

class GetAIToolScreenshotTask
{
    public static function handle($url_to_crawl_id, $ai_tool_id)
    {
        $url_to_crawl = UrlToCrawl::find($url_to_crawl_id);

        if (is_null($url_to_crawl)) {
            return;
        }

        $ai_tool = AiTool::find($ai_tool_id);

        if (is_null($ai_tool)) {
            return;
        }

        $userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36';

        $browsershot = Browsershot::url($url_to_crawl->url)
            ->timeout(30)
            ->emulateMedia('screen')
            ->userAgent($userAgent)
            ->windowSize(1024, 576)  // Set window size
            ->waitUntilNetworkIdle();  // Wait until all resources are loaded

        if (app()->environment() == 'local') {
            $browsershot->setNodeBinary(config('platform.general.node_binary'))->setNpmBinary(config('platform.general.npm_binary'));
        }

        $retries = 0;
        $maxRetries = 1;

        while ($retries < $maxRetries) {
            try {
                $image_content = $browsershot->screenshot();
                break;  // Exit the loop if the screenshot method succeeds
            } catch (Exception $e) {
                $retries++;
                if ($retries === $maxRetries) {
                    throw new Exception("Failed to take a screenshot after $maxRetries attempts: ".$e->getMessage(), 0, $e);
                }
            }
        }

        $image = Image::make($image_content)
            ->resize(1024, null, function ($constraint) {
                $constraint->aspectRatio();
            })
            ->stream('webp', 80);

        $image_file_name = str_slug($ai_tool->tool_name).'-'.epoch_now_timestamp().'.webp';

        $upload_status = OSSUploader::uploadFile(
            config('platform.uploads.ai_tools.screenshot.driver'),
            config('platform.uploads.ai_tools.screenshot.path'),
            $image_file_name,
            $image);

        if ($upload_status) {
            $ai_tool->screenshot_img = $image_file_name;
        }

        if ($ai_tool->isDirty()) {
            $ai_tool->save();
        }

        return $ai_tool;

    }
}
