<?php

namespace App\Jobs;

use App\Models\AiJob;
use App\Models\SocialComment;
use App\Models\AutoReplySuggestion;
use App\Models\AutoReplySetting;
use App\Services\ProfanityFilterService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class GenerateAutoReplySuggestionsJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $commentId;
    protected $brandId;
    protected $creatorId;

    /**
     * Create a new job instance.
     *
     * @param int $commentId
     * @param int|null $brandId
     * @param int|null $creatorId
     * @return void
     */
    public function __construct($commentId, $brandId = null, $creatorId = null)
    {
        $this->commentId = $commentId;
        $this->brandId = $brandId;
        $this->creatorId = $creatorId;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // Get the comment
        $comment = SocialComment::find($this->commentId);
        
        if (!$comment) {
            Log::error("Social comment not found: " . $this->commentId);
            return;
        }
        
        // Get settings (either brand or creator)
        if ($this->creatorId) {
            $settings = AutoReplySetting::where('creator_id', $this->creatorId)->first();
            $entityType = 'creator';
            $entityId = $this->creatorId;
        } else {
            $settings = AutoReplySetting::where('brand_id', $this->brandId)->first();
            $entityType = 'brand';
            $entityId = $this->brandId;
        }
        
        if (!$settings || !$settings->enabled) {
            Log::info("Auto-reply not enabled for {$entityType}: " . $entityId);
            return;
        }
        
        // Initialize profanity filter
        $profanityFilter = new ProfanityFilterService();
        
        // Set entity-specific words if available
        if ($this->creatorId && !empty($settings->creator_guidelines)) {
            // Extract creator-specific words from guidelines
            $entityWords = [];
            foreach ($settings->creator_guidelines as $guideline) {
                // Simple extraction - in a real implementation, this would be more sophisticated
                $words = explode(' ', strtolower($guideline));
                foreach ($words as $word) {
                    $word = trim($word, '.,!?;:"');
                    if (strlen($word) > 3) { // Only consider words longer than 3 characters
                        $entityWords[] = $word;
                    }
                }
            }
            $profanityFilter->setBrandSpecificWords(array_unique($entityWords));
        } elseif (!empty($settings->brand_guidelines)) {
            // Extract brand-specific words from guidelines
            $entityWords = [];
            foreach ($settings->brand_guidelines as $guideline) {
                // Simple extraction - in a real implementation, this would be more sophisticated
                $words = explode(' ', strtolower($guideline));
                foreach ($words as $word) {
                    $word = trim($word, '.,!?;:"');
                    if (strlen($word) > 3) { // Only consider words longer than 3 characters
                        $entityWords[] = $word;
                    }
                }
            }
            $profanityFilter->setBrandSpecificWords(array_unique($entityWords));
        }
        
        // Check if comment contains profanity
        if ($profanityFilter->hasProfanity($comment->content)) {
            Log::info("Skipping comment due to profanity: " . $comment->id);
            return;
        }
        
        // Check if comment matches any rule-based triggers to skip
        if ($this->shouldSkipComment($comment, $settings)) {
            Log::info("Skipping comment due to rule-based triggers: " . $comment->id);
            return;
        }
        
        // Create AI job for generating reply suggestion
        $aiJob = AiJob::create([
            'job_id' => (string) Str::uuid(),
            'type' => 'auto_reply_suggestion',
            'status' => 'queued',
            'brand_id' => $this->brandId,
            'creator_id' => $this->creatorId,
            'proposal_id' => null,
            'result_text' => null,
            'result_meta' => null,
            'provider' => null,
            'error_message' => null,
            'token_usage' => 0,
        ]);
        
        // Update status to generating
        $aiJob->update(['status' => 'generating']);
        
        try {
            // Generate auto-reply suggestion
            $suggestionData = $this->generateReplySuggestion($comment, $settings);
            
            // Save auto-reply suggestion to database
            $autoReplySuggestion = AutoReplySuggestion::create([
                'social_comment_id' => $comment->id,
                'brand_id' => $this->brandId,
                'creator_id' => $this->creatorId,
                'ai_job_id' => $aiJob->id,
                'suggested_reply' => $suggestionData['reply'],
                'confidence_score' => $suggestionData['confidence'],
                'brand_voice' => $settings->brand_voice,
                'preferred_tone' => $settings->preferred_tone ?? 'casual',
                'is_approved' => false,
                'is_posted' => false,
                'meta' => [
                    'reasoning' => $suggestionData['reasoning'] ?? null,
                ],
            ]);
            
            // Auto-approve if confidence is high enough and setting is enabled
            if ($settings->auto_approve_high_confidence && 
                $suggestionData['confidence'] >= $settings->auto_approve_confidence_threshold) {
                $autoReplySuggestion->update(['is_approved' => true]);
            }
            
            // Update AI job with results
            $aiJob->update([
                'status' => 'ready',
                'result_text' => 'Generated auto-reply suggestion',
                'result_meta' => [
                    'confidence_score' => $suggestionData['confidence'],
                    'auto_approved' => $autoReplySuggestion->is_approved,
                ],
                'provider' => 'openai-gpt-4',
                'token_usage' => 150, // Rough estimation
                'completed_at' => now(),
            ]);
            
            // Log token usage for cost tracking
            Log::info("Auto-reply suggestion generated for comment: " . $comment->id . " with token usage: 150");
        } catch (\Exception $e) {
            // Update AI job with error
            $aiJob->update([
                'status' => 'failed',
                'error_message' => $e->getMessage(),
            ]);
            
            Log::error("Auto-reply suggestion generation failed for comment: " . $comment->id . " with error: " . $e->getMessage());
        }
    }
    
    /**
     * Check if comment should be skipped based on settings.
     *
     * @param SocialComment $comment
     * @param AutoReplySetting $settings
     * @return bool
     */
    protected function shouldSkipComment($comment, $settings)
    {
        // Check excluded keywords
        if (!empty($settings->excluded_keywords)) {
            $content = strtolower($comment->content);
            foreach ($settings->excluded_keywords as $keyword) {
                if (strpos($content, strtolower($keyword)) !== false) {
                    return true;
                }
            }
        }
        
        // Check rule-based triggers
        if (!empty($settings->rule_based_triggers)) {
            // Rule: skip comments from specific users
            if (isset($settings->rule_based_triggers['exclude_users'])) {
                $excludedUsers = $settings->rule_based_triggers['exclude_users'];
                if (in_array($comment->author_username, $excludedUsers)) {
                    return true;
                }
            }
            
            // Rule: skip comments with mentions
            if (isset($settings->rule_based_triggers['exclude_mentions']) &&
                $settings->rule_based_triggers['exclude_mentions']) {
                if (strpos($comment->content, '@') !== false) {
                    return true;
                }
            }
            
            // Rule: auto-reply to FAQs
            if (isset($settings->rule_based_triggers['auto_reply_faq']) &&
                $settings->rule_based_triggers['auto_reply_faq']) {
                // Check if comment is a FAQ
                $faqs = [
                    'how much', 'what is the price', 'when will', 'how long',
                    'do you ship', 'return policy', 'warranty', 'contact'
                ];
                
                $content = strtolower($comment->content);
                foreach ($faqs as $faq) {
                    if (strpos($content, $faq) !== false) {
                        // For FAQs, we don't skip - we auto-generate a specific reply
                        return false;
                    }
                }
            }
        }
        
        return false;
    }
    
    /**
     * Generate reply suggestion based on comment and settings.
     *
     * @param SocialComment $comment
     * @param AutoReplySetting $settings
     * @return array
     */
    protected function generateReplySuggestion($comment, $settings)
    {
        // In a real implementation, this would call an AI service
        // For now, we'll generate mock suggestions with varying confidence
        
        // Check if this is an FAQ that should be auto-replied
        $isFAQ = false;
        $faqReply = '';
        
        if (!empty($settings->rule_based_triggers['auto_reply_faq']) &&
            $settings->rule_based_triggers['auto_reply_faq']) {
            $faqs = [
                'how much' => 'Our products range from $20-$100 depending on the model. Check our website for current pricing!',
                'what is the price' => 'Our products range from $20-$100 depending on the model. Check our website for current pricing!',
                'when will' => 'We typically ship within 1-2 business days. Delivery takes 3-7 business days depending on your location.',
                'how long' => 'We typically ship within 1-2 business days. Delivery takes 3-7 business days depending on your location.',
                'do you ship' => 'Yes, we ship worldwide! Shipping is free for orders over $50.',
                'return policy' => 'We offer a 30-day return policy. Items must be in original condition with tags attached.',
                'warranty' => 'All our products come with a 1-year limited warranty. Contact support for warranty claims.',
                'contact' => 'You can reach our support team at support@ourbrand.com or call us at (555) 123-4567.'
            ];
            
            $content = strtolower($comment->content);
            foreach ($faqs as $faq => $response) {
                if (strpos($content, $faq) !== false) {
                    $isFAQ = true;
                    $faqReply = $response;
                    break;
                }
            }
        }
        
        // Simple logic to determine confidence based on content
        $confidence = 85; // Default confidence
        
        // Adjust confidence based on content
        if (stripos($comment->content, 'question') !== false ||
            stripos($comment->content, 'help') !== false ||
            stripos($comment->content, 'how') !== false) {
            $confidence = 95; // Higher confidence for questions
        } elseif (stripos($comment->content, 'spam') !== false ||
                  stripos($comment->content, 'buy') !== false) {
            $confidence = 30; // Lower confidence for potential spam
        }
        
        // For FAQs, we have high confidence
        if ($isFAQ) {
            $confidence = 98;
            $reply = $faqReply;
        } else {
            // Generate reply based on entity voice/tone
            if ($this->creatorId) {
                $reply = $this->generateReplyBasedOnTone($comment, $settings->preferred_tone ?? 'casual');
            } else {
                $reply = $this->generateReplyBasedOnVoice($comment, $settings->brand_voice);
            }
        }
        
        return [
            'reply' => $reply,
            'confidence' => $confidence,
            'reasoning' => $isFAQ ? 'Auto-generated FAQ response' : ($this->creatorId ? 'Generated based on creator tone: ' . ($settings->preferred_tone ?? 'casual') : 'Generated based on brand voice: ' . $settings->brand_voice),
        ];
    }
    
    /**
     * Generate reply based on creator tone.
     *
     * @param SocialComment $comment
     * @param string $tone
     * @return string
     */
    protected function generateReplyBasedOnTone($comment, $tone)
    {
        $replies = [
            'casual' => [
                "Thanks for your comment, {$comment->author_name}! 😊",
                "Appreciate you taking the time to comment, {$comment->author_name}!",
                "Thanks for sharing, {$comment->author_name}! Means a lot to me.",
                "Hey {$comment->author_name}, thanks for the comment! 👋",
                "Love seeing your comment here, {$comment->author_name}! ❤️"
            ],
            'friendly' => [
                "Wow, thanks so much for your comment, {$comment->author_name}! You just made my day! 🌟",
                "Hey there {$comment->author_name}! I'm so glad you reached out. Thanks for the kind words! ✨",
                "Your comment literally put a smile on my face, {$comment->author_name}! Thanks for being awesome! 😄",
                "Aww, thank you for your comment, {$comment->author_name}! You're the best! 💖",
                "Thanks for taking the time to comment, {$comment->author_name}! It means everything to me! 🙏"
            ],
            'humorous' => [
                "Haha, thanks for the comment, {$comment->author_name}! You crack me up! 😂",
                "Well, well, well... look who left a comment! Thanks {$comment->author_name}, you're a legend! 🦸",
                "Thanks for your comment, {$comment->author_name}! I was just thinking about you! (Not really, but nice to see you!) 😉",
                "Comment received and filed under 'Made My Day'! Thanks {$comment->author_name}! 📁",
                "You've got my attention with that comment, {$comment->author_name}! What's next, a marriage proposal? 💍"
            ]
        ];
        
        $toneReplies = $replies[$tone] ?? $replies['casual'];
        return $toneReplies[array_rand($toneReplies)];
    }
    
    /**
     * Generate reply based on brand voice.
     *
     * @param SocialComment $comment
     * @param string $voice
     * @return string
     */
    protected function generateReplyBasedOnVoice($comment, $voice)
    {
        $replies = [
            'professional' => [
                "Thank you for your comment, {$comment->author_name}. We appreciate your feedback and will get back to you shortly.",
                "We've received your comment and our team is looking into it. Thank you for reaching out.",
                "Thanks for sharing your thoughts with us. We value your input and will respond as soon as possible."
            ],
            'friendly' => [
                "Thanks for your comment, {$comment->author_name}! We're glad you reached out. We'll get back to you soon!",
                "Hey {$comment->author_name}, we saw your comment! Thanks for sharing. We'll respond shortly.",
                "Thanks for reaching out, {$comment->author_name}! We appreciate your feedback and will get back to you soon."
            ],
            'witty' => [
                "Thanks for the comment, {$comment->author_name}! You've got our attention. We'll be in touch soon!",
                "We saw your comment, {$comment->author_name}! Thanks for sharing. We're cooking up a response now.",
                "Thanks for reaching out, {$comment->author_name}! Your comment just made our day. Response coming soon!"
            ]
        ];
        
        $voiceReplies = $replies[$voice] ?? $replies['professional'];
        return $voiceReplies[array_rand($voiceReplies)];
    }
}