<?php

namespace App\Traits;

use Exception;
use OpenAI;
use OpenAI\Exceptions\ErrorException;

trait AiTrait
{
    private function getOpenAIClient()
    {
        $apiKey = get_config('openai_secret_key'); // Recommended: Store in config
        
        if (empty($apiKey) || str_contains($apiKey, 'your-api-key-here')) {
            throw new Exception('OpenAI API key is missing or not configured');
        }

        return OpenAI::client($apiKey);
    }

    private function generateContent(string $type, string $title, string $systemPrompt): string
    {
        try {
            if (empty($title)) {
                return "Error: Please provide a {$type} title first.";
            }

            $client = $this->getOpenAIClient();

            $response = $client->chat()->create([
                'model' => 'gpt-3.5-turbo',
                'messages' => [
                    ['role' => 'system', 'content' => $systemPrompt],
                    ['role' => 'user', 'content' => "Title: {$title}"],
                ],
                'temperature' => 0.7,
                'max_tokens' => 200,
            ]);

            return $response->choices[0]->message->content ?? "Failed to generate {$type} description.";

        } catch (ErrorException $e) {
            if (str_contains($e->getMessage(), 'Incorrect API key provided')) {
                return 'Error: Invalid OpenAI API key. Please check your configuration.';
            }
            return "Error: Failed to generate {$type} description. " . $e->getMessage();
        } catch (Exception $e) {
            return "Error: {$e->getMessage()}";
        }
    }

    // Regular Descriptions
    public function generateMovieDescription(array $request): string
    {
        return $this->generateContent(
            'movie',
            $request['title'] ?? '',
            'You are an expert movie description writer. Create engaging 2-3 paragraph descriptions that:
             - Capture the mood and tone
             - Briefly introduce main characters
             - Hint at the central conflict
             - Avoid major spoilers
             - Make readers eager to watch'
        );
    }

    public function generateTvSeriesDescription(array $request): string
    {
        return $this->generateContent(
            'TV series',
            $request['title'] ?? '',
            'You are a professional TV series summarizer. Write compelling 2-3 paragraph descriptions that:
             - Introduce the show\'s premise
             - Describe the main characters
             - Highlight what makes it unique
             - Mention the tone (dramatic, comedic, etc.)
             - Avoid spoilers beyond season 1'
        );
    }

    public function generateBlogDescription(array $request): string
    {
        return $this->generateContent(
            'blog post',
            $request['title'] ?? '',
            'You are a skilled blog content writer. Create engaging introductions that:
             - Clearly state the article\'s purpose
             - Highlight what readers will learn
             - Use an inviting, conversational tone
             - Include potential pain points it addresses
             - Keep it under 500 words'
        );
    }

    // Meta Descriptions
    public function generateMovieMetaDescription(array $request): string
    {
        return $this->generateContent(
            'movie meta',
            $request['title'] ?? '',
            'You are an SEO specialist. Create compelling meta descriptions (under 160 characters) that:
             - Include the title naturally
             - Highlight key attractions (stars, director, awards)
             - Use power words (thrilling, heartwarming, etc.)
             - Create urgency to watch
             - Format: "Title (Year) | Key elements | Call to action"'
        );
    }

    public function generateTvSeriesMetaDescription(array $request): string
    {
        return $this->generateContent(
            'TV series meta',
            $request['title'] ?? '',
            'You are an SEO specialist. Create TV show meta descriptions (under 160 characters) that:
             - Include the title and premiere year
             - Mention genre and tone
             - Note notable cast/creators
             - Highlight what makes it binge-worthy
             - Format: "Title (Year) | Genre | Unique selling point | Stream now"'
        );
    }

    public function generateBlogMetaDescription(array $request): string
    {
        return $this->generateContent(
            'blog meta',
            $request['title'] ?? '',
            'You are an SEO specialist. Create blog meta descriptions (under 160 characters) that:
             - Include primary keyword naturally
             - Clearly state the benefit of reading
             - Use action verbs (learn, discover, etc.)
             - Create curiosity gap
             - Format: "Want to [solve problem]? Learn how [solution] in this complete guide."'
        );
    }

    // Live TV Methods
    public function generateLiveTvDescription(array $request): string
    {
        return $this->generateContent(
            'live TV channel',
            $request['title'] ?? '',
            'You are a live TV programming expert. Create engaging descriptions that:
             - Identify the channel type (news, sports, entertainment, etc.)
             - Highlight key programming highlights
             - Mention any unique selling points
             - Describe the typical viewer experience
             - Keep it under 150 words'
        );
    }

    public function generateLiveTvMetaDescription(array $request): string
    {
        return $this->generateContent(
            'live TV meta',
            $request['title'] ?? '',
            'You are an SEO specialist for TV networks. Create compelling meta descriptions (under 120 characters) that:
             - Start with the channel name
             - Highlight top shows/features
             - Include broadcast times if relevant
             - Use action words (Watch, Stream, Enjoy)
             - Format: "[Channel]: Watch [show1], [show2] and more. Stream live 24/7"'
        );
    }
}