<?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, $categories)
    {
        //$excerpt = substr($excerpt, 0, 1500);

        $category_str = implode("|", $categories);

        $system_prompt = '
          You are tasked with writing a product introduction & review article using the provided excerpt. Write as if you are reviewing the product by a third party, avoiding pronouns. Emphasize the product\'s performance, features, and notable aspects. Do not mention marketplace-related information. Return the output as a minified JSON in this format:
              {"category": "($category_str)","title": "(Start with product name, 60-70 characters)","excerpt": "(150-160 characters, do not start with a verb)","cliffhanger": "(70-80 characters, enticing sentence)","body": "(Markdown, 700-900 words)"}

              Mandatory Requirements:
              - Language: US grade 8-9 English
              - Use these sections when applicable:
                -- ### Introduction
                -- ### Overview
                -- ### Specifications (use valid Markdown table. Two columns: Features and Specifications. Use `| --- | --- |` as a separator.)
                -- ### Price (in given currency)
                -- ### (Choose one: Should I Buy?, Conclusion, Final Thoughts, Our Verdict)
              - Only use facts from the provided excerpt
              - Don\'t use titles inside the markdown body
              - Use \'###\' for all article sections
              - Pick the closest provided category
              - Do not use newline in the JSON structure
      ';

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

        if (count($photos) > 0) {
            $system_prompt .= '- Include 3 markdown images with the article title as caption in every section, excluding Introduction.\n';
            $user_prompt .= "\n\MARKDOWN IMAGES\n------------\n";
            foreach ($photos as $photo) {
                $user_prompt .= "{$photo}\n";
            }
        }

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

        // 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;

    }
}
