<?php

namespace App\Helpers\FirstParty\AI;

use Illuminate\Support\Facades\Http;

class OpenAI
{
    public static function getMemeKeywords(string $name, string $description)
    {
        $apiKey = config('services.openai.api_key'); // Make sure to set this in config/services.php

        $response = Http::withHeaders([
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer '.$apiKey,
        ])->post('https://api.openai.com/v1/responses', [
            'model' => 'gpt-4.1-nano',
            'input' => [
                [
                    'role' => 'system',
                    'content' => [
                        [
                            'type' => 'input_text',
                            'text' => "You are a meme annotation assistant. Given a meme name and description, you must populate three keyword categories: action_keywords: List specific actions being performed in the meme (e.g., wearing, singing, dancing) emotion_keywords: List feelings and emotions conveyed by the meme (e.g., joy, excitement, sadness) misc_keywords: List core identifying elements - keep this concise and focused on essential references only (e.g., main subjects, key objects, proper nouns) Format your response with clear category labels. Be precise and avoid over-elaborating, especially in misc_keywords. Example: Input: \"7th Element OIIA Cat, OIIA cat wearing 7th element head ban and sings 7th element song chorous with OIIA sounds\" Output: action_keywords: wearing, singing, performing emotion_keywords: excitement, joy, playfulness misc_keywords: cat, 7th element, headband, OIIA. the description may also have spelling and grammar issues, please fix it\n\nreturn in json:\n{\ndescription: \"\",\naction_keywords:[],\nemotion_keywords:[],\nmisc_keywords:[],\n}",
                        ],
                    ],
                ],
                [
                    'role' => 'user',
                    'content' => [
                        [
                            'type' => 'input_text',
                            'text' => "Name: $name\nDescription: $description",
                        ],
                    ],
                ],
            ],
            'text' => [
                'format' => [
                    'type' => 'json_object',
                ],
            ],
            'reasoning' => new \stdClass,
            'tools' => [],
            'temperature' => 1,
            'max_output_tokens' => 2048,
            'top_p' => 1,
            'store' => true,
        ]);

        return $response->json();
    }

    public static function getSingleMemeGenerator($user_prompt)
    {

        $caption_descriptions = [
            'A humorous, funny one-liner that starts with "When you", describes a specific visual or situational moment, avoids vagueness, and ends with no punctuation',
            'A POV meme that starts with "POV: ", clearly describes a specific scenario or feeling with high context, and ends with no punctuation',
            'A humorous, funny one-liner that starts with "I", grounded in a relatable, situational experience with visual context, and ends with no punctuation',
            'A humorous, funny one-liner that starts with "You", focused on a clear, specific reaction or moment, and ends with no punctuation',
            'A humorous, funny one-liner with no punctuation that describes a vivid, realistic scenario or reaction in a clearly defined context',
        ];

        $response = Http::withHeaders([
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer '.env('OPENAI_API_KEY'),
        ])
            ->post('https://api.openai.com/v1/responses', [
                'model' => 'gpt-4.1-nano',
                'input' => [
                    [
                        'role' => 'system',
                        'content' => [
                            [
                                'type' => 'input_text',
                                'text' => '"You are an AI meme writer for a video meme generator.\n\nYour task is to generate a JSON array containing a unique, short-form workplace-related video meme ideas.\n\nEach meme object must include the following fields, with the format shown below. Each field contains an inline description of the type of content it must generate.\n\nReturn **only** a Markdown code block containing valid JSON with inline content guidance (as strings). Do not add any commentary or explanation outside the code block.\n\n- All memes must be funny, relatable, and clearly connected to the provided topic.\n- Use realistic but exaggerated expressions and settings to match meme-style content.\n- Style should suit video formats like TikTok, Instagram Reels, or YouTube Shorts."',
                            ],
                        ],
                    ],
                    [
                        'role' => 'user',
                        'content' => [
                            [
                                'type' => 'input_text',
                                'text' => $user_prompt,
                            ],
                        ],
                    ],
                ],
                'text' => [
                    'format' => [
                        'type' => 'json_schema',
                        'name' => 'meme_generator_single_1',
                        'strict' => true,
                        'schema' => [
                            'type' => 'object',
                            'properties' => [
                                'caption' => [
                                    'type' => 'string',
                                    'description' => $caption_descriptions[rand(0, count($caption_descriptions) - 1)],
                                ],
                                'primary_keyword_type' => [
                                    'type' => 'string',
                                    'description' => 'Primary keyword type, choose only between: (action|emotion|misc)',
                                ],
                                'action_keywords' => [
                                    'type' => 'array',
                                    'description' => 'List specific actions being performed in the meme (e.g., wearing, singing, dancing)',
                                    'items' => [
                                        'type' => 'string',
                                    ],
                                ],
                                'emotion_keywords' => [
                                    'type' => 'array',
                                    'description' => 'List feelings and emotions conveyed by the meme (e.g., joy, excitement, sadness)',
                                    'items' => [
                                        'type' => 'string',
                                    ],
                                ],
                                'misc_keywords' => [
                                    'type' => 'array',
                                    'description' => 'List core identifying elements - keep this concise and focused on essential references only (e.g., main subjects, key objects, proper nouns)',
                                    'items' => [
                                        'type' => 'string',
                                    ],
                                ],
                                'background' => [
                                    'type' => 'string',
                                    'description' => "Use this exact structure: 'Location: [setting only, e.g., empty office with cluttered desk and monitor]'. Do not mention people, animals, actions, or any living beings. No verbs. No brand names. Only interior spaces or physical locations. Examples: 'Location: quiet office cubicle with headset and papers'.",

                                ],
                                'keywords' => [
                                    'type' => 'array',
                                    'description' => 'Relevant lowercase tags for the meme (e.g., "burnout", "email fail", "meetings")',
                                    'items' => [
                                        'type' => 'string',
                                    ],
                                ],
                            ],
                            'required' => [
                                'caption',
                                'primary_keyword_type',
                                'action_keywords',
                                'emotion_keywords',
                                'misc_keywords',
                                'background',
                                'keywords',
                            ],
                            'additionalProperties' => false,
                        ],
                    ],
                ],
                'reasoning' => (object) [],
                'tools' => [],
                'temperature' => 1,
                'max_output_tokens' => 2048,
                'top_p' => 1,
                'store' => true,
            ]);

        // Get the response data
        $data = $response->json();

        // Check if the request was successful
        if ($response->successful()) {
            // Handle successful response
            return $data;
        } else {
            // Handle error
            throw new \Exception('API request failed: '.$response->body());
        }
    }

    public static function getOpenAIOutput($data)
    {
        // dump($data);

        $output = null;

        $response_type = data_get($data, 'output.0.content.0.type', null);

        if ($response_type === 'output_text') {
            $output = data_get($data, 'output.0.content.0.text', null);
        } elseif ($response_type === 'refusal') {
            $output = data_get($data, 'output.0.content.0.refusal', null);
        }

        return $output;
    }
}
