<?php

namespace App\Jobs\Tasks;

use App\Helpers\FirstParty\OpenAI\OpenAI;
use App\Helpers\FirstParty\OSSUploader\OSSUploader;
use App\Jobs\SchedulePublishPost;
use App\Models\Category;
use App\Models\Entity;
use App\Models\Post;
use App\Models\PostCategory;
use App\Models\PostEntity;
use App\Models\SerpUrlResearch;
use App\Models\ServiceCostUsage;
use Exception;
use Illuminate\Support\Facades\Http;
use Image;

class FillPostMetadataTask
{
    public static function handle(int $post_id)
    {
        $post = Post::find($post_id);

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

        if (! is_null($post->metadata)) {
            $post_meta_response = $post->metadata;
        } else {
            $post_meta_response = OpenAI::getArticleMeta($post->body, 1536, 30);

            if ((isset($post_meta_response->output)) && (! is_null($post_meta_response->output))) {
                $service_cost_usage = new ServiceCostUsage;
                $service_cost_usage->cost = $post_meta_response->cost;
                $service_cost_usage->name = 'openai-getArticleMeta';
                $service_cost_usage->reference_1 = 'post';
                $service_cost_usage->reference_2 = strval($post->id);
                $service_cost_usage->output = $post_meta_response;
                $service_cost_usage->save();
            }
        }

        //dump($post_meta_response);

        if ((isset($post_meta_response->output)) && (! is_null($post_meta_response->output))) {

            $post->metadata = $post_meta_response;

            if (isset($post_meta_response->output->keywords)) {
                if (count($post_meta_response->output->keywords) > 0) {
                    $post->keywords = $post_meta_response->output->keywords;

                    $post->main_keyword = $post_meta_response->output->keywords[0];
                }
            }

            if (isset($post_meta_response->output->title)) {
                if ((is_empty($post->title)) && (! is_empty($post_meta_response->output->title))) {
                    $post->title = $post_meta_response->output->title;
                }
            }

            if (isset($post_meta_response->output->summary)) {
                if (! is_empty($post_meta_response->output->summary)) {
                    $post->bites = $post_meta_response->output->summary;
                }
            }

        }

        if (is_empty($post->slug)) {
            $post->slug = str_slug($post->title);
        }

        if (is_empty($post->featured_image)) {
            $post = self::setPostImage($post);
        }

        if (isset($post_meta_response->output->society_impact)) {
            if (! is_empty($post_meta_response->output->society_impact)) {
                $post->society_impact = $post_meta_response->output->society_impact;
            }
        }

        if (isset($post_meta_response->output->society_impact_level)) {
            if (! is_empty($post_meta_response->output->society_impact_level)) {
                $post->society_impact_level = $post_meta_response->output->society_impact_level;
            }
        }

        if ($post->save()) {

            // Set Category

            $category_name = 'Updates';

            if ((isset($post_meta_response->output->category)) && (! is_empty($post_meta_response->output->category))) {
                $category_name = $post_meta_response?->output?->category;
            }

            $category = Category::where('name', $category_name)->first();

            if (is_null($category)) {
                $category = Category::where('name', 'Updates')->first();
            }

            // Set Post Category
            $post_category = PostCategory::where('post_id', $post->id)->first();

            if (is_null($post_category)) {
                $post_category = new PostCategory;
                $post_category->post_id = $post->id;
            }
            $post_category->category_id = $category->id;

            $post_category->save();

            // Set Post Entities
            if (isset($post_meta_response->output->entities)) {
                $entity_names = [];

                if (is_array($post_meta_response->output->entities)) {
                    $entity_names = $post_meta_response->output->entities;
                }

                if (count($entity_names) > 0) {
                    $previous_post_entities = PostEntity::where('post_id', $post->id)->delete();

                    foreach ($entity_names as $entity_name) {
                        $entity_name = trim($entity_name);

                        $entity = Entity::where('name', $entity_name)->first();

                        if (is_null($entity)) {
                            $entity = new Entity;
                            $entity->name = $entity_name;
                            $entity->slug = str_slug($entity_name);
                            $entity->save();
                        }

                        $post_entity = PostEntity::where('post_id', $post->id)
                            ->where('entity_id', $entity->id)
                            ->first();

                        if (is_null($post_entity)) {
                            $post_entity = new PostEntity;
                            $post_entity->post_id = $post->id;
                            $post_entity->entity_id = $entity->id;
                            $post_entity->save();
                        }
                    }
                }
            }

            // Set Schedule Publish
            SchedulePublishPost::dispatch($post->id, 'future')->onQueue('default')->onConnection('default');
        }

    }

    private static function setPostImage($post)
    {
        $serp_url_researches = SerpUrlResearch::where('serp_url_id', $post->serp_url_id)->get();

        $main_image_url = null;

        foreach ($serp_url_researches as $serp_url_research) {
            if (! is_empty($serp_url_research->main_image)) {
                if (is_valid_url($serp_url_research->main_image)) {

                    if (is_empty($serp_url_research->main_image)) {
                        continue;
                    }

                    $main_image_url = $serp_url_research->main_image;

                    $image_response = Http::timeout(300)->withHeaders([
                        'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36',
                    ])->get($main_image_url);

                    $image_content = $image_response->body();

                    // Get the size of the image content in KB
                    $imageSizeInKb = strlen($image_response->body()) / 1024;

                    // Skip this iteration if the image exceeds the maximum size
                    if ($imageSizeInKb > 1024) {
                        continue;
                    }

                    $canvas_width = 1080;
                    $canvas_height = 608;

                    $thumb_width = 540;
                    $thumb_height = 78;

                    // Create an image from the fetched content
                    $image = Image::make($image_content);

                    // Check if the image is wider than it is tall (landscape orientation)
                    if ($image->width() > $image->height()) {
                        // Resize the image to fill the canvas width while maintaining aspect ratio
                        $image->resize($canvas_width, null, function ($constraint) {
                            $constraint->aspectRatio();
                        });
                    } else {
                        // Resize the image to fill the canvas height while maintaining aspect ratio
                        $image->resize(null, $canvas_height, function ($constraint) {
                            $constraint->aspectRatio();
                        });
                    }

                    // Fit the image to the canvas size, without gaps
                    $image->fit($canvas_width, $canvas_height, function ($constraint) {
                        $constraint->upsize();
                    });

                    // Create a thumbnail by cloning the original image and resizing it
                    $thumb = clone $image;
                    $thumb->resize($thumb_width, $thumb_height, function ($constraint) {
                        $constraint->aspectRatio();
                        $constraint->upsize();
                    });

                    // Create a image filename
                    $epoch_now_timestamp = epoch_now_timestamp();
                    $filename = $post->slug.'-'.$epoch_now_timestamp.'.jpg';
                    $thumb_filename = $post->slug.'-'.$epoch_now_timestamp.'_thumb.jpg';

                    OSSUploader::uploadFile('r2', 'post_images_2/', $filename, (string) $image->stream('jpeg', 75));
                    OSSUploader::uploadFile('r2', 'post_images_2/', $thumb_filename, (string) $thumb->stream('jpeg', 50));

                    $post->featured_image = 'post_images_2/'.$filename;

                    $image->destroy();

                    try {
                        break;
                    } catch (Exception $e) {
                        continue;
                    }

                }
            }
        }

        return $post;
    }
}
