<?php

namespace Database\Seeders;

use App\Models\AiTemplate;
use App\Models\User;
use App\Models\Platform;
use App\Models\AiSetting;
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;
use Faker\Factory as Faker;

class DemoAiTemplateSeeder extends Seeder
{
    /**
     * Run the database seeds for AI templates.
     */
    public function run(): void
    {
        $faker = Faker::create();

        // Create AI settings first
        $this->createAiSettings();

        $users = User::all();
        $platforms = Platform::all();

        if ($users->isEmpty() || $platforms->isEmpty()) {
            $this->command->warn('Please run DemoUserSeeder and PlatformSeeder first!');
            return;
        }

        $templateData = [
            'Social Media Posts' => [
                'Promotional Post Generator' => 'Create an engaging promotional post for {product_name} that highlights its key features: {key_features}. Target audience: {target_audience}. Tone: {tone}. Include relevant hashtags and a call-to-action.',
                'Story Content Creator' => 'Generate a compelling story post about {topic} for {platform}. Make it personal and engaging with {tone} tone. Include relevant emojis and keep it under {character_limit} characters.',
                'Product Launch Announcement' => 'Create an exciting product launch announcement for {product_name}. Highlight the problem it solves: {problem}. Include launch date: {launch_date} and special offers: {offers}.',
                'Educational Content Generator' => 'Create educational content about {topic} that provides value to {target_audience}. Include 3-5 key points and actionable tips. Tone should be {tone} and informative.',
                'Engagement Booster Post' => 'Generate an engaging post that encourages interaction about {topic}. Include questions, polls, or call-to-action that drives comments and shares. Target: {target_audience}.',
            ],
            'Marketing Campaigns' => [
                'Email Marketing Subject Lines' => 'Generate 5 compelling email subject lines for {campaign_type} targeting {audience}. Focus on {main_benefit} and create urgency around {deadline}. Avoid spam words.',
                'Ad Copy Generator' => 'Create persuasive ad copy for {product_service} targeting {target_audience}. Highlight main benefit: {main_benefit}. Include strong call-to-action and keep under {character_limit} characters.',
                'Campaign Hashtag Creator' => 'Generate 10-15 relevant hashtags for {campaign_name} campaign. Mix popular and niche hashtags. Target audience: {target_audience}. Campaign goal: {campaign_goal}.',
                'Seasonal Campaign Content' => 'Create seasonal campaign content for {season_holiday} promoting {product_service}. Incorporate seasonal themes and emotions. Target: {target_audience}. Tone: {tone}.',
                'Influencer Outreach Template' => 'Create a personalized influencer outreach message for {influencer_name} about {collaboration_type}. Mention their recent content: {recent_content}. Offer: {collaboration_offer}.',
            ],
            'Content Strategy' => [
                'Content Calendar Ideas' => 'Generate content ideas for {industry} business targeting {audience}. Provide themes for {time_period}. Include mix of educational, promotional, and engaging content types.',
                'Blog Post Outline Creator' => 'Create a detailed blog post outline for "{blog_topic}". Target audience: {target_audience}. Include introduction, 5-7 main points, conclusion, and SEO considerations.',
                'Video Script Generator' => 'Write a {video_length} video script about {topic} for {platform}. Include hook, main content, and call-to-action. Tone: {tone}. Target audience: {target_audience}.',
                'Caption Variations Generator' => 'Create 5 different caption variations for {content_type} about {topic}. Vary the tone from {tone1} to {tone2}. Include relevant hashtags and emojis.',
                'Content Repurposing Ideas' => 'Suggest 5 ways to repurpose {original_content} across different platforms. Consider {platform_list} and adapt format for each platform\'s best practices.',
            ],
            'Customer Engagement' => [
                'Customer Testimonial Request' => 'Create a friendly message requesting testimonial from {customer_name} about {product_service}. Mention their positive experience with {specific_feature}. Make it easy to respond.',
                'FAQ Response Generator' => 'Generate helpful responses to frequently asked questions about {product_service}. Question: {customer_question}. Provide clear, friendly answer with additional resources.',
                'Community Management Response' => 'Create appropriate responses to {comment_type} comments on social media post about {topic}. Maintain {brand_tone} and provide value while encouraging further engagement.',
                'Thank You Message Creator' => 'Generate personalized thank you messages for {customer_action}. Customer: {customer_name}. Include appreciation for {specific_action} and encourage {next_action}.',
                'Feedback Collection Template' => 'Create a survey request for collecting feedback about {product_service}. Make it engaging and explain how feedback will be used. Offer incentive: {incentive}.',
            ],
            'Sales & Support' => [
                'Sales Pitch Generator' => 'Create a compelling sales pitch for {product_service} targeting {prospect_type}. Address their main pain point: {pain_point}. Highlight unique value: {unique_value}.',
                'Follow-up Email Template' => 'Generate follow-up email for {prospect_name} after {interaction_type}. Reference previous conversation about {topic} and propose next steps: {next_steps}.',
                'Objection Handler Responses' => 'Create responses to common sales objections: "{objection}". Provide empathetic acknowledgment and compelling counter-arguments with supporting evidence.',
                'Customer Onboarding Message' => 'Create welcome message for new customer {customer_name}. Explain next steps for {product_service} and provide helpful resources. Set expectations for {timeline}.',
                'Support Ticket Response' => 'Generate helpful support response for customer issue: {customer_issue}. Provide clear solution steps and offer additional assistance. Maintain empathetic and professional tone.',
            ],
        ];

        $templateCounter = 0;

        foreach ($templateData as $category => $templates) {
            foreach ($templates as $name => $prompt) {
                foreach ($users->take(3) as $user) { // Create templates for first 3 users
                    foreach ($platforms->random(2) as $platform) { // Each template for 2 random platforms
                        $templateCounter++;

                        AiTemplate::create([
                            'uid' => Str::uuid(),
                            'user_id' => $user->id,
                            'platform_id' => $platform->id,
                            'name' => $name . ' - ' . ucfirst($platform->name),
                            'prompt' => $prompt,
                            'created_at' => $faker->dateTimeBetween('-3 months', 'now'),
                            'updated_at' => now(),
                        ]);
                    }
                }
            }
        }

        $this->command->info("Created {$templateCounter} AI templates across {$users->count()} users!");
    }

    /**
     * Create AI settings for different providers
     */
    private function createAiSettings(): void
    {
        $aiSettings = [
            [
                'module' => 'content_generation',
                'provider' => 'openai',
                'config' => json_encode([
                    'api_key' => 'sk-demo-key-not-real',
                    'model' => 'gpt-4',
                    'max_tokens' => 1000,
                    'temperature' => 0.7,
                    'top_p' => 1,
                    'frequency_penalty' => 0,
                    'presence_penalty' => 0,
                ]),
            ],
            [
                'module' => 'image_generation',
                'provider' => 'dalle',
                'config' => json_encode([
                    'api_key' => 'sk-demo-key-not-real',
                    'model' => 'dall-e-3',
                    'size' => '1024x1024',
                    'quality' => 'standard',
                    'n' => 1,
                ]),
            ],
            [
                'module' => 'text_analysis',
                'provider' => 'openai',
                'config' => json_encode([
                    'api_key' => 'sk-demo-key-not-real',
                    'model' => 'gpt-3.5-turbo',
                    'max_tokens' => 500,
                    'temperature' => 0.3,
                ]),
            ],
            [
                'module' => 'hashtag_generation',
                'provider' => 'custom',
                'config' => json_encode([
                    'max_hashtags' => 15,
                    'include_trending' => true,
                    'include_niche' => true,
                    'avoid_banned' => true,
                ]),
            ],
            [
                'module' => 'content_optimization',
                'provider' => 'anthropic',
                'config' => json_encode([
                    'api_key' => 'demo-key-not-real',
                    'model' => 'claude-3-sonnet',
                    'max_tokens' => 1000,
                    'temperature' => 0.5,
                ]),
            ],
        ];

        foreach ($aiSettings as $setting) {
            AiSetting::updateOrCreate(
                [
                    'module' => $setting['module'],
                    'provider' => $setting['provider'],
                ],
                [
                    'config' => $setting['config'],
                ]
            );
        }
    }
}