<?php

namespace App\Services;

use App\Models\Ad;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class AdCopyGeneratorService
{
    /**
     * Generate multiple ad copy variants using AI.
     *
     * @param Ad $ad
     * @param int $numVariants
     * @return array
     */
    public function generateVariants(Ad $ad, int $numVariants = 3): array
    {
        $variants = [];
        
        // Define different creative approaches for variants
        $approaches = [
            'benefit_focused' => 'Focus on the key benefits and value proposition',
            'emotional' => 'Create an emotional connection with the audience',
            'urgency' => 'Create a sense of urgency and scarcity',
            'social_proof' => 'Emphasize social proof and testimonials',
            'problem_solution' => 'Highlight the problem and present the solution',
        ];

        $approachKeys = array_keys($approaches);
        
        for ($i = 0; $i < $numVariants; $i++) {
            $approach = $approaches[$approachKeys[$i % count($approachKeys)]];
            
            try {
                $variant = $this->generateSingleVariant($ad, $approach, $i + 1);
                $variants[] = $variant;
            } catch (\Exception $e) {
                Log::error('Failed to generate ad variant', [
                    'ad_id' => $ad->id,
                    'variant_number' => $i + 1,
                    'error' => $e->getMessage()
                ]);
                
                // Fallback to template-based generation
                $variants[] = $this->generateFallbackVariant($ad, $approach, $i + 1);
            }
        }

        return $variants;
    }

    /**
     * Generate a single ad variant using AI.
     *
     * @param Ad $ad
     * @param string $approach
     * @param int $variantNumber
     * @return array
     */
    protected function generateSingleVariant(Ad $ad, string $approach, int $variantNumber): array
    {
        $prompt = $this->buildPrompt($ad, $approach);
        
        // Call AI service (OpenAI, Anthropic, or custom AI endpoint)
        $response = $this->callAIService($prompt);
        
        // Parse the AI response
        $parsedResponse = $this->parseAIResponse($response);
        
        // Add predicted metrics based on approach and content analysis
        $predictedMetrics = $this->predictMetrics($parsedResponse, $approach);
        
        return [
            'headline' => $parsedResponse['headline'],
            'body' => $parsedResponse['body'],
            'cta' => $parsedResponse['cta'],
            'predicted_metrics' => $predictedMetrics,
            'approach' => $approach,
        ];
    }

    /**
     * Build the AI prompt for generating ad copy.
     *
     * @param Ad $ad
     * @param string $approach
     * @return string
     */
    protected function buildPrompt(Ad $ad, string $approach): string
    {
        return <<<PROMPT
Generate compelling ad copy for the following product/service:

Product/Service Information:
{$ad->product_info}

Target Audience:
{$ad->audience}

Tone:
{$ad->tone}

Creative Approach:
{$approach}

Please generate:
1. A compelling headline (max 60 characters)
2. Body copy (max 150 characters)
3. A clear call-to-action (max 20 characters)

Format your response as JSON with keys: headline, body, cta

Ensure the copy is:
- Engaging and attention-grabbing
- Aligned with the specified tone
- Tailored to the target audience
- Following the creative approach specified
- Compliant with advertising standards
PROMPT;
    }

    /**
     * Call the AI service to generate content.
     *
     * @param string $prompt
     * @return string
     */
    protected function callAIService(string $prompt): string
    {
        // Check if OpenAI API key is configured
        $apiKey = config('services.openai.api_key');
        
        if (!$apiKey) {
            throw new \Exception('AI service not configured');
        }

        try {
            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . $apiKey,
                'Content-Type' => 'application/json',
            ])->timeout(30)->post('https://api.openai.com/v1/chat/completions', [
                'model' => 'gpt-4',
                'messages' => [
                    [
                        'role' => 'system',
                        'content' => 'You are an expert advertising copywriter specializing in creating high-converting ad copy.'
                    ],
                    [
                        'role' => 'user',
                        'content' => $prompt
                    ]
                ],
                'temperature' => 0.8,
                'max_tokens' => 500,
            ]);

            if ($response->successful()) {
                return $response->json()['choices'][0]['message']['content'];
            }

            throw new \Exception('AI service returned error: ' . $response->body());
        } catch (\Exception $e) {
            Log::error('AI service call failed', ['error' => $e->getMessage()]);
            throw $e;
        }
    }

    /**
     * Parse the AI response into structured data.
     *
     * @param string $response
     * @return array
     */
    protected function parseAIResponse(string $response): array
    {
        // Try to parse as JSON first
        $decoded = json_decode($response, true);
        
        if ($decoded && isset($decoded['headline'], $decoded['body'], $decoded['cta'])) {
            return [
                'headline' => substr($decoded['headline'], 0, 60),
                'body' => substr($decoded['body'], 0, 150),
                'cta' => substr($decoded['cta'], 0, 20),
            ];
        }

        // Fallback: try to extract from text
        preg_match('/headline["\s:]+([^"\n]+)/i', $response, $headlineMatch);
        preg_match('/body["\s:]+([^"\n]+)/i', $response, $bodyMatch);
        preg_match('/cta["\s:]+([^"\n]+)/i', $response, $ctaMatch);

        return [
            'headline' => isset($headlineMatch[1]) ? trim($headlineMatch[1], '",') : 'Discover More',
            'body' => isset($bodyMatch[1]) ? trim($bodyMatch[1], '",') : 'Learn about our amazing product.',
            'cta' => isset($ctaMatch[1]) ? trim($ctaMatch[1], '",') : 'Learn More',
        ];
    }

    /**
     * Predict performance metrics based on content analysis.
     *
     * @param array $content
     * @param string $approach
     * @return array
     */
    protected function predictMetrics(array $content, string $approach): array
    {
        // Base metrics
        $baseCTR = 0.5;
        $baseConversionRate = 0.02;

        // Adjust based on approach
        $approachMultipliers = [
            'benefit_focused' => ['ctr' => 1.2, 'conversion' => 1.3],
            'emotional' => ['ctr' => 1.4, 'conversion' => 1.1],
            'urgency' => ['ctr' => 1.5, 'conversion' => 1.4],
            'social_proof' => ['ctr' => 1.3, 'conversion' => 1.5],
            'problem_solution' => ['ctr' => 1.1, 'conversion' => 1.2],
        ];

        $multiplier = $approachMultipliers[$approach] ?? ['ctr' => 1.0, 'conversion' => 1.0];

        // Analyze content quality
        $headlineLength = strlen($content['headline']);
        $bodyLength = strlen($content['body']);
        
        // Optimal lengths boost performance
        $lengthBoost = 1.0;
        if ($headlineLength >= 30 && $headlineLength <= 50) {
            $lengthBoost += 0.1;
        }
        if ($bodyLength >= 80 && $bodyLength <= 130) {
            $lengthBoost += 0.1;
        }

        // Check for power words
        $powerWords = ['free', 'new', 'proven', 'guaranteed', 'exclusive', 'limited', 'save', 'now'];
        $powerWordCount = 0;
        foreach ($powerWords as $word) {
            if (stripos($content['headline'] . ' ' . $content['body'], $word) !== false) {
                $powerWordCount++;
            }
        }
        $powerWordBoost = 1.0 + ($powerWordCount * 0.05);

        // Calculate final predictions
        $predictedCTR = round($baseCTR * $multiplier['ctr'] * $lengthBoost * $powerWordBoost, 2);
        $predictedConversion = round($baseConversionRate * $multiplier['conversion'] * $lengthBoost, 4);

        return [
            'predicted_ctr' => min($predictedCTR, 5.0), // Cap at 5%
            'predicted_conversion_rate' => min($predictedConversion, 0.1), // Cap at 10%
            'confidence_score' => round(($lengthBoost + $powerWordBoost) / 2, 2),
            'approach' => $approach,
        ];
    }

    /**
     * Generate a fallback variant when AI service fails.
     *
     * @param Ad $ad
     * @param string $approach
     * @param int $variantNumber
     * @return array
     */
    protected function generateFallbackVariant(Ad $ad, string $approach, int $variantNumber): array
    {
        $templates = [
            'benefit_focused' => [
                'headline' => 'Transform Your {product} Experience Today',
                'body' => 'Discover the benefits that {audience} love. Get started now!',
                'cta' => 'Get Started',
            ],
            'emotional' => [
                'headline' => 'Feel the Difference with {product}',
                'body' => 'Join thousands who have transformed their lives. Your journey starts here.',
                'cta' => 'Join Now',
            ],
            'urgency' => [
                'headline' => 'Limited Time: {product} Special Offer',
                'body' => 'Don\'t miss out! Exclusive offer for {audience}. Act now!',
                'cta' => 'Claim Offer',
            ],
            'social_proof' => [
                'headline' => 'Trusted by Thousands: {product}',
                'body' => 'See why {audience} choose us. Join our community today!',
                'cta' => 'Learn More',
            ],
            'problem_solution' => [
                'headline' => 'Solve Your {problem} with {product}',
                'body' => 'The solution {audience} have been waiting for. Try it today!',
                'cta' => 'Try Now',
            ],
        ];

        $template = $templates[$approach] ?? $templates['benefit_focused'];
        
        // Simple placeholder replacement
        $productName = $this->extractProductName($ad->product_info);
        $audienceType = $this->extractAudienceType($ad->audience);

        return [
            'headline' => str_replace(['{product}', '{audience}', '{problem}'], 
                [$productName, $audienceType, 'challenges'], 
                $template['headline']),
            'body' => str_replace(['{product}', '{audience}'], 
                [$productName, $audienceType], 
                $template['body']),
            'cta' => $template['cta'],
            'predicted_metrics' => [
                'predicted_ctr' => rand(30, 80) / 100,
                'predicted_conversion_rate' => rand(1, 5) / 100,
                'confidence_score' => 0.6,
                'approach' => $approach,
            ],
            'approach' => $approach,
        ];
    }

    /**
     * Extract product name from product info.
     *
     * @param string $productInfo
     * @return string
     */
    protected function extractProductName(string $productInfo): string
    {
        $words = explode(' ', $productInfo);
        return ucfirst($words[0] ?? 'Product');
    }

    /**
     * Extract audience type from audience description.
     *
     * @param string $audience
     * @return string
     */
    protected function extractAudienceType(string $audience): string
    {
        $words = explode(' ', $audience);
        return strtolower($words[0] ?? 'customers');
    }
}