<?php

namespace App\Jobs\Tasks;

use App\Helpers\FirstParty\ImageGen\ImageGen;
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;
        $image_ref_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;
                    }

                    try {

                        $main_image_url = $serp_url_research->main_image;
                        $image_ref_url = $serp_url_research->url;

                        $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;
                        }

                        $post_description = strtoupper(now()->format('j M')).' • '.$post->main_keyword.' • '.markdown_min_read($post->body);

                        $image = ImageGen::getMainImage($image_content, 1007, 567);
                        $og_image = ImageGen::getOpenGraphImage($image_content, 1007, 567, $post->title, $post_description);

                        $epoch_now_timestamp = epoch_now_timestamp();
                        $filename = $post->slug.'-'.$epoch_now_timestamp.'.jpg';
                        $og_filename = $post->slug.'-'.$epoch_now_timestamp.'_og.jpg';

                        OSSUploader::uploadFile('r2', 'post_images/', $filename, (string) $image->stream('jpeg', 75));
                        OSSUploader::uploadFile('r2', 'post_images/', $og_filename, (string) $og_image->stream('jpeg', 75));

                        $post->featured_image = 'post_images/'.$filename;
                        $post->image_ref_url = $image_ref_url;

                        $image->destroy();

                        break;

                    } catch (Exception $e) {
                        continue;
                    }

                }
            }
        }

        return $post;
    }
}
