<?php

namespace Modules\Dummy\Database\Seeders\Modules\AiSocialSuites\versions\v6_9_0;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Http;
use Modules\AiSocialSuites\Entities\SocialAccount;
use Modules\AiSocialSuites\Entities\SocialPost;
use Carbon\Carbon;

class AiSocialSuitesSeeder extends Seeder
{
    private bool $fresh = false;

    /** Cached image URLs/paths so we don't fetch one per post (major speedup). */
    private array $imagePool = [];

    /** Number of images to pre-fetch and reuse for all posts. */
    private const IMAGE_POOL_SIZE = 10;

    /** Number of posts to create (fewer = faster seeding). */
    private const POSTS_TO_CREATE = 50;
    

    public function run(bool $fresh = false): void
    {
        $this->fresh = $fresh;

        if ($this->fresh) {
            $this->clearExistingData();
        }

        $this->createSocialAccounts(2);
        $this->createSocialPosts(2);
    }

    private function getOnlineImageUrl(): string
    {
        $width = rand(800, 1200);
        $height = rand(600, 800);
        return "https://picsum.photos/{$width}/{$height}?random=" . rand(1, 99999);
    }

    /**
     * Pre-fetch a small pool of images once; reused for all posts so we don't do 50+ HTTP requests.
     */
    private function buildImagePool(int $size): void
    {
        $this->imagePool = [];
        for ($i = 0; $i < $size; $i++) {
            $onlineUrl = $this->getOnlineImageUrl();
            $stored = $this->storeOnlineImageToStorage($onlineUrl);
            if ($stored !== '') {
                $this->imagePool[] = $this->metaImageUrl($stored);
            } else {
                $stored = $this->storeDefaultImageToStorage();
                if ($stored !== '') {
                    $this->imagePool[] = $this->metaImageUrl($stored);
                } else {
                    $this->imagePool[] = $this->getOnlineImageUrl();
                }
            }
        }
    }

    private function storeOnlineImageToStorage(string $imageUrl): string
    {
        $dateDir = date('Ymd');
        $filename = md5(uniqid((string) mt_rand(), true)) . '.jpg';
        // Use same path format as PostController so objectStorage()->url() resolves correctly
        $storagePath = 'public/uploads/aiImages/seed/' . $dateDir . '/' . $filename;

        try {
            $response = Http::timeout(5)
                ->withHeaders(['User-Agent' => 'Laravel-Seeder/1.0'])
                ->get($imageUrl);
            if (!$response->successful()) {
                return '';
            }
            $content = $response->body();
            if (function_exists('objectStorage')) {
                objectStorage()->put($storagePath, $content);
                return $storagePath;
            }
            // Fallback: write to public dir; return full URL so views use it as-is (objectStorage would point elsewhere)
            $relativePath = 'uploads/aiImages/seed/' . $dateDir . '/';
            $targetDir = public_path($relativePath);
            if (!File::isDirectory($targetDir)) {
                File::ensureDirectoryExists($targetDir);
            }
            if (File::put($targetDir . $filename, $content) !== false) {
                return asset($relativePath . $filename);
            }
        } catch (\Throwable $e) {
        }

        return '';
    }

    private function storeDefaultImageToStorage(): string
    {
        $defaults = [
            'assets/image/gallery-image-one.png',
            'assets/image/gallery-image-two.png',
            'assets/image/banner-1.png',
            'assets/image/banner-2.png',
            'assets/image/profile-pic.png',
        ];
        $dateDir = date('Ymd');
        foreach ($defaults as $rel) {
            $src = public_path($rel);
            if (File::exists($src) && File::isFile($src)) {
                $ext = pathinfo($src, PATHINFO_EXTENSION) ?: 'jpg';
                $filename = md5(uniqid((string) mt_rand(), true)) . '.' . $ext;
                $storagePath = 'public/uploads/aiImages/seed/' . $dateDir . '/' . $filename;
                if (function_exists('objectStorage')) {
                    objectStorage()->put($storagePath, File::get($src));
                    return $storagePath;
                }
                $relativePath = 'uploads/aiImages/seed/' . $dateDir . '/';
                $targetDir = public_path($relativePath);
                if (!File::isDirectory($targetDir)) {
                    File::ensureDirectoryExists($targetDir);
                }
                if (File::copy($src, $targetDir . $filename)) {
                    return asset($relativePath . $filename);
                }
            }
        }
        return '';
    }

    /**
     * Store relative path as-is so objectStorage()->url() is used by views/transformers.
     * Only return full URL when we have an external placeholder (e.g. picsum).
     */
    private function metaImageUrl(string $stored): string
    {
        if (str_starts_with($stored, 'http://') || str_starts_with($stored, 'https://')) {
            return $stored;
        }
        // Paths under public/uploads/ or uploads/ are resolved by objectStorage()->url() in the app
        return $stored;
    }

    private function clearExistingData(): void
    {
        \Modules\AiSocialSuites\Entities\SocialPost::query()->delete();
        \Modules\AiSocialSuites\Entities\SocialAccount::query()->delete();

        \Illuminate\Support\Facades\DB::table('social_post_metas')->delete();
        \Illuminate\Support\Facades\DB::table('social_account_metas')->delete();
    }

    private function createSocialAccounts(int $userId): void
    {
        $accountConfigs = $this->getAccountConfigurations();

        foreach ($accountConfigs as $config) {
            $account = SocialAccount::create([
                'user_id' => $userId,
                'account_name' => $config['account_name'],
                'handle' => $config['handle'],
                'platform' => $config['platform'],
                'platform_account_id' => $config['platform_account_id'],
                'profile_picture' => 'https://picsum.photos/200/200?random=' . rand(1, 99999),
                'status' => 'active',
                'access_token' => 'fake_token_' . rand(1000, 9999),
                'refresh_token' => 'fake_refresh_' . rand(1000, 9999),
                'token_expires_at' => Carbon::now()->addDays(rand(30, 90)),
                'last_synced_at' => Carbon::now()->subHours(rand(1, 24)),
            ]);

            $this->addAccountMetaData($account);
            $account->save();
        }
    }

    private function getAccountConfigurations(): array
    {
        return [
            [
                'account_name' => 'Tech Innovator Hub',
                'handle' => '@techinnovator',
                'platform' => 'twitter',
                'platform_account_id' => '1234567890',
            ],
            [
                'account_name' => 'Creative Studio',
                'handle' => '@creativestudio',
                'platform' => 'instagram',
                'platform_account_id' => '9876543210',
            ],
            [
                'account_name' => 'Business Insights',
                'handle' => 'business-insights-official',
                'platform' => 'linkedin',
                'platform_account_id' => 'linkedin_12345',
            ],
            [
                'account_name' => 'Daily Updates',
                'handle' => 'dailyupdates',
                'platform' => 'facebook',
                'platform_account_id' => 'facebook_67890',
            ],
            [
                'account_name' => 'Marketing Pro',
                'handle' => '@marketingpro',
                'platform' => 'twitter',
                'platform_account_id' => 'twitter_54321',
            ],
            [
                'account_name' => 'Art Gallery',
                'handle' => '@artgallery',
                'platform' => 'instagram',
                'platform_account_id' => 'instagram_13579',
            ],
            [
                'account_name' => 'Tech Solutions Inc',
                'handle' => 'tech-solutions-inc',
                'platform' => 'linkedin',
                'platform_account_id' => 'linkedin_98765',
            ],
        ];
    }

    private function addAccountMetaData(SocialAccount $account): void
    {
        $metaData = $this->getPlatformMetaData($account->platform);

        foreach ($metaData as $key => $value) {
            $account->setMeta($key, $value);
        }
    }

    private function getPlatformMetaData(string $platform): array
    {
        return match ($platform) {
            'twitter' => [
                'followers_count' => rand(1000, 50000),
                'following_count' => rand(500, 2000),
                'tweets_count' => rand(1000, 10000),
                'verified' => (string) rand(0, 1),
            ],
            'instagram' => [
                'followers_count' => rand(5000, 100000),
                'following_count' => rand(300, 1000),
                'posts_count' => rand(500, 2000),
                'is_business_account' => (string) rand(0, 1),
            ],
            'linkedin' => [
                'connections_count' => rand(500, 30000),
                'posts_count' => rand(100, 1000),
                'company_size' => ['1-10', '11-50', '51-200', '201-500', '501-1000', '1001-5000', '5000+'][rand(0, 6)],
            ],
            'facebook' => [
                'likes_count' => rand(1000, 50000),
                'posts_count' => rand(200, 2000),
                'page_category' => ['Business', 'Brand', 'Community', 'Entertainment', 'Education'][rand(0, 4)],
            ],
            default => [],
        };
    }

    private function createSocialPosts(int $userId): void
    {
        $accounts = SocialAccount::with('metas')->where('user_id', $userId)->get();

        if ($accounts->isEmpty()) {
            return;
        }

        $this->buildImagePool(self::IMAGE_POOL_SIZE);

        $postTemplates = $this->getPostTemplates();
        $postsToCreate = self::POSTS_TO_CREATE;

        for ($i = 0; $i < $postsToCreate; $i++) {
            $account = $accounts->random();
            $template = $postTemplates[array_rand($postTemplates)];
            $status = $this->getRandomStatus();
            $createdAt = Carbon::now()->subDays(rand(0, 30))->subHours(rand(0, 23));

            $postData = $this->buildPostData($userId, $account, $template, $status, $createdAt);
            $post = SocialPost::create($postData);

            $this->addPostMetaData($post, $template);
            $post->save();
        }
    }

    private function buildPostData(int $userId, SocialAccount $account, array $template, string $status, Carbon $createdAt): array
    {
        $postData = [
            'user_id' => $userId,
            'social_account_id' => $account->id,
            'title' => $template['title'],
            'content' => $template['content'],
            'platform' => $account->platform,
            'media_type' => $template['media_type'],
            'status' => $status,
            'created_at' => $createdAt,
            'updated_at' => $createdAt,
        ];

        return match ($status) {
            'published' => array_merge($postData, [
                'posted_at' => $createdAt->copy()->addMinutes(rand(5, 1440)),
                'platform_post_id' => $account->platform . '_post_' . rand(10000, 99999),
            ]),
            'scheduled' => array_merge($postData, [
                'scheduled_for' => Carbon::now()->addDays(rand(1, 7))->addHours(rand(0, 23)),
            ]),
            'failed' => array_merge($postData, [
                'error_message' => $this->getRandomErrorMessage(),
            ]),
            default => $postData,
        };
    }

    private function getPostTemplates(): array
    {
        return [
            [
                'title' => 'Exciting Product Launch!',
                'content' => '🚀 We\'re thrilled to announce the launch of our latest innovation! This breakthrough product combines cutting-edge technology with user-friendly design. Stay tuned for more updates! #Innovation #TechLaunch',
                'media_type' => 'image',
            ],
            [
                'title' => 'Team Building Event',
                'content' => 'Had an amazing team building event today! Grateful to work with such talented and dedicated professionals. Teamwork makes the dream work! 🙌 #TeamBuilding #CompanyCulture',
                'media_type' => 'image',
            ],
            [
                'title' => 'Industry Insights',
                'content' => 'The future of digital marketing is evolving rapidly. Here are 5 key trends to watch in 2024: 1️⃣ AI-powered personalization 2️⃣ Video content dominance 3️⃣ Social commerce growth 4️⃣ Privacy-first approaches 5️⃣ Influencer authenticity. What do you think? #DigitalMarketing #Trends2024',
                'media_type' => 'text',
            ],
            [
                'title' => 'Customer Success Story',
                'content' => 'Another success story from our amazing clients! "This solution transformed our workflow completely. Highly recommend!" - Happy Customer. Thank you for being part of our journey! 💪 #CustomerSuccess #Testimonial',
                'media_type' => 'image',
            ],
            [
                'title' => 'Behind the Scenes',
                'content' => 'Ever wondered what goes on behind the scenes? Here\'s a glimpse of our creative process in action. From concept to creation, every detail matters! 🎨✨ #BehindTheScenes #CreativeProcess',
                'media_type' => 'image',
            ],
            [
                'title' => 'Market Analysis',
                'content' => 'Market analysis shows significant growth in sustainable technologies. Our commitment to eco-friendly solutions has never been more important. What are your thoughts on green innovation? 🌱 #Sustainability #GreenTech',
                'media_type' => 'link',
            ],
            [
                'title' => 'Weekend Inspiration',
                'content' => 'As we wrap up another productive week, here\'s some inspiration for the weekend: "Success is not final, failure is not fatal: It is the courage to continue that counts." - Winston Churchill. Have a great weekend! 🌟 #Motivation #WeekendVibes',
                'media_type' => 'text',
            ],
            [
                'title' => 'Product Demo Video',
                'content' => 'Check out our latest product demo! See how easy it is to streamline your workflow with our intuitive interface. The future of productivity is here! 🎥 #ProductDemo #Productivity',
                'media_type' => 'video',
            ],
            [
                'title' => 'Industry Event Recap',
                'content' => 'What an incredible industry conference! Met amazing people, learned cutting-edge insights, and discovered new opportunities. The networking was phenomenal. Grateful for the experience! 🤝 #Networking #IndustryEvent',
                'media_type' => 'image',
            ],
            [
                'title' => 'Quick Tips',
                'content' => '💡 Quick productivity tip: Break down large tasks into smaller, manageable chunks. You\'ll be amazed at how much more you can accomplish! What\'s your favorite productivity hack? #ProductivityTips #WorkSmarter',
                'media_type' => 'text',
            ],
            [
                'title' => 'Company Milestone',
                'content' => '🎉 Celebrating a major milestone today! 10,000+ happy customers and counting. Thank you for being part of our journey. Here\'s to many more successes ahead! #Milestone #Growth',
                'media_type' => 'image',
            ],
            [
                'title' => 'Thought Leadership',
                'content' => 'In today\'s rapidly changing business landscape, adaptability is key. Here are three strategies for staying ahead of the competition: 1) Embrace digital transformation 2) Invest in continuous learning 3) Foster innovation culture. #ThoughtLeadership #BusinessStrategy',
                'media_type' => 'text',
            ],
            [
                'title' => 'Office Tour',
                'content' => 'Welcome to our workspace! This is where the magic happens. Modern design meets productive environment. Love coming to work every day! 🏢 #OfficeTour #Workspace',
                'media_type' => 'image',
            ],
            [
                'title' => 'Client Meeting',
                'content' => 'Productive client meeting today! Always exciting to collaborate with forward-thinking businesses. Looking forward to the partnership ahead! 🤝 #ClientMeeting #BusinessDevelopment',
                'media_type' => 'image',
            ],
            [
                'title' => 'Technology Update',
                'content' => 'Exciting updates coming to our platform! New features include enhanced analytics, improved user interface, and faster performance. Can\'t wait to share more details! 🔄 #TechUpdate #PlatformNews',
                'media_type' => 'image',
            ],
            [
                'title' => 'Community Engagement',
                'content' => 'Thank you to everyone who participated in our community survey! Your feedback helps us build better products. Here are some key insights we gathered 📊 #CommunityEngagement #UserFeedback',
                'media_type' => 'link',
            ],
            [
                'title' => 'Remote Work Tips',
                'content' => 'Working remotely successfully takes planning and discipline. Here are our top 5 tips: 1) Create a dedicated workspace 2) Establish routine 3) Stay connected with team 4) Take regular breaks 5) Maintain work-life balance. #RemoteWork #WorkTips',
                'media_type' => 'text',
            ],
            [
                'title' => 'Partnership Announcement',
                'content' => 'Thrilled to announce our new partnership! Combining forces to deliver even better solutions to our customers. The future looks bright! 🌟 #Partnership #Collaboration',
                'media_type' => 'image',
            ],
            [
                'title' => 'Data Visualization',
                'content' => 'Check out this fascinating data visualization of our growth over the past year. Numbers don\'t lie - we\'re moving in the right direction! 📈 #DataVisualization #Growth',
                'media_type' => 'image',
            ],
            [
                'title' => 'Holiday Greetings',
                'content' => 'Season\'s greetings from our team to yours! Wishing you a joyful holiday season and a prosperous new year. Thank you for being part of our journey! 🎄✨ #HolidayGreetings #ThankYou',
                'media_type' => 'image',
            ],
        ];
    }

    private function getRandomStatus(): string
    {
        $statuses = [
            'published' => 60,
            'scheduled' => 25,
            'draft' => 10,
            'failed' => 5,
        ];

        $rand = rand(1, 100);
        $cumulative = 0;

        foreach ($statuses as $status => $weight) {
            $cumulative += $weight;
            if ($rand <= $cumulative) {
                return $status;
            }
        }

        return 'draft';
    }

    private function getRandomErrorMessage(): string
    {
        $errors = [
            'Authentication failed. Please reconnect your account.',
            'Post content violates platform guidelines.',
            'Media file is too large. Maximum size allowed: 10MB.',
            'Rate limit exceeded. Please try again later.',
            'Invalid media format. Supported formats: JPG, PNG, MP4.',
            'Post scheduling failed due to platform maintenance.',
            'Insufficient permissions to post on this account.',
        ];

        return $errors[array_rand($errors)];
    }

    private function addPostMetaData(SocialPost $post, array $template): void
    {
        $metaData = [];

        $resolveAndStoreImage = function () {
            if (!empty($this->imagePool)) {
                $displayUrl = $this->imagePool[array_rand($this->imagePool)];
                return [
                    'image_url' => $displayUrl,
                    'media_urls' => [$displayUrl],
                ];
            }
            $onlineUrl = $this->getOnlineImageUrl();
            $stored = $this->storeOnlineImageToStorage($onlineUrl);
            if ($stored === '') {
                $stored = $this->storeDefaultImageToStorage();
            }
            $displayUrl = $stored !== ''
                ? $this->metaImageUrl($stored)
                : $this->getOnlineImageUrl();
            return [
                'image_url' => $displayUrl,
                'media_urls' => [$displayUrl],
            ];
        };

        $resolved = $resolveAndStoreImage();
        $metaData['image_url'] = $resolved['image_url'];
        $metaData['media_urls'] = $resolved['media_urls'];
        $metaData['thumbnail'] = $resolved['image_url'];
        $metaData['alt_text'] = $this->generateImageAltText($post->title);

        if ($template['media_type'] === 'video') {
            $metaData['video_duration'] = rand(30, 300);
        }

        if ($template['media_type'] === 'link') {
            $metaData['link_url'] = 'https://example.com/article-' . rand(100, 999);
            $metaData['link_title'] = 'Related Article: ' . substr($post->title, 0, 30);
            $metaData['link_description'] = substr($post->content, 0, 150) . '...';
        }

        if ($post->platform === 'instagram') {
            $metaData['instagram_media_type'] = rand(1, 3);
        }

        if ($post->status === 'published') {
            $metaData = array_merge($metaData, $this->generateEngagementMetrics($post->platform));
        }

        if (str_contains($post->content, '#')) {
            preg_match_all('/#(\w+)/', $post->content, $hashtags);
            $metaData['hashtags'] = $hashtags[1] ?? [];
        }

        foreach ($metaData as $key => $value) {
            $post->setMeta($key, $value);
        }
    }

    private function generateEngagementMetrics(string $platform): array
    {
        $baseMetrics = [
            'likes_count' => rand(10, 500),
            'comments_count' => rand(0, 50),
            'shares_count' => rand(0, 100),
            'impressions_count' => rand(1000, 10000),
        ];

        switch ($platform) {
            case 'instagram':
                $baseMetrics['likes_count'] = rand(50, 2000);
                $baseMetrics['comments_count'] = rand(5, 200);
                $baseMetrics['impressions_count'] = rand(5000, 50000);
                break;
            case 'twitter':
                $baseMetrics['likes_count'] = rand(5, 500);
                $baseMetrics['shares_count'] = rand(1, 200);
                $baseMetrics['impressions_count'] = rand(1000, 20000);
                break;
            case 'facebook':
                $baseMetrics['likes_count'] = rand(20, 1000);
                $baseMetrics['comments_count'] = rand(0, 100);
                $baseMetrics['shares_count'] = rand(0, 150);
                $baseMetrics['impressions_count'] = rand(2000, 30000);
                break;
            case 'linkedin':
                $baseMetrics['likes_count'] = rand(10, 300);
                $baseMetrics['comments_count'] = rand(0, 30);
                $baseMetrics['shares_count'] = rand(0, 50);
                $baseMetrics['impressions_count'] = rand(500, 5000);
                break;
        }

        return $baseMetrics;
    }

    private function generateImageAltText(string $title): string
    {
        $altTexts = [
            'Product launch announcement image',
            'Team celebration photo',
            'Professional headshot',
            'Office workspace photo',
            'Company branding image',
            'Event photography',
            'Product showcase',
            'Team collaboration image',
            'Corporate meeting photo',
            'Business achievement graphic',
        ];

        $title = strtolower($title);
        if (str_contains($title, 'launch') || str_contains($title, 'product')) {
            return 'Product launch announcement image';
        } elseif (str_contains($title, 'team') || str_contains($title, 'event')) {
            return 'Team celebration photo';
        } elseif (str_contains($title, 'behind') || str_contains($title, 'scenes')) {
            return 'Behind the scenes office photo';
        } elseif (str_contains($title, 'success') || str_contains($title, 'customer')) {
            return 'Customer success story image';
        }

        return $altTexts[array_rand($altTexts)];
    }

}