<?php

namespace App\Helpers\FirstParty\OpenAI;

use Exception;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class OpenAI
{
    public static function writeProductArticle($excerpt, $photos)
    {
        $excerpt = substr($excerpt, 0, 1500);

        $system_prompt = '
          You are tasked with writing a comprehensive product introduction & review article using the provided excerpt. Write as if you are reviewing the product by a third party, but no pronouns.The emphasis should be on the performance, features, and notable aspects of the product. The review must not delve into marketplace-related information. Return the output in the following json format:\n\n
            {"title": "(Article Title, start with product name, 60-70 characters)","excerpt": "(One sentence summary, 150-160 characters of an article, do not use start sentence with verb.)","cliffhanger": "(One sentence 70-80 characters of article, cliff-hanging sentence to attract readers)","body": "(Markdown format, 700-900 word count)"}\n\n
            Mandatory Requirements:\n
            - Write in US grade 8-9 English\n
            - Use the following sections whenever applicable:\n
            -- ### Introduction\n
            -- ### Overview\n
            -- ### Specifications (use valid Markdown table format with header and seperator) +  explanation\n
            -- ### Price\n
            -- ### Should I Buy?\n
            - do not make up facts, use facts provided by excerpt only\n
            - No article titles inside markdown\n
            - All article sections use ###
            
      ';

        $user_prompt = "EXCERPT\n------------\n{$excerpt}\n";

        if (count($photos) > 0) {
            $system_prompt .= '- Add at least 3 markdown images with article title as caption in every section except for Introduction';
            $user_prompt .= "\n\nPHOTOS\n------------\n";
            foreach ($photos as $photo) {
                $user_prompt .= "{$photo}\n";
            }
        }

        $output = (self::chatCompletion($system_prompt, $user_prompt, 'gpt-3.5-turbo', 4000));

        // dump($user_prompt);
        // dd($output);

        if (! is_null($output)) {
            try {
                return json_decode($output, false, 512, JSON_THROW_ON_ERROR);
            } catch (Exception $e) {
                Log::error($output);
                inspector()->reportException($e);

                return null;
            }

        }

        return null;

    }

    public static function chatCompletion($system_prompt, $user_prompt, $model, $max_token = 2500)
    {
        try {
            $response = Http::timeout(800)->withToken(config('platform.ai.openai.api_key'))
                ->post('https://api.openai.com/v1/chat/completions', [
                    'model' => $model,
                    'max_tokens' => $max_token,
                    'messages' => [
                        ['role' => 'system', 'content' => $system_prompt],
                        ['role' => 'user', 'content' => $user_prompt],
                    ],
                ]);

            //dd($response->body());

            $json_response = json_decode($response->body(), false, 512, JSON_THROW_ON_ERROR);

            $reply = $json_response?->choices[0]?->message?->content;

            return $reply;
        } catch (Exception $e) {
            Log::error($response->body());
            inspector()->reportException($e);
            throw ($e);
        }

        return null;

    }
}
