from django.core.management.base import BaseCommand
from blog.models import BlogAuthor, BlogCategory, BlogTag, BlogPost
from django.utils import timezone
from datetime import timedelta


class Command(BaseCommand):
    help = 'Populate database with sample blog data'

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('Starting to populate blog data...'))

        # Clear existing data
        BlogPost.objects.all().delete()
        BlogTag.objects.all().delete()
        BlogCategory.objects.all().delete()
        BlogAuthor.objects.all().delete()

        # Create Authors
        authors_data = [
            {
                'name': 'Sarah Johnson',
                'email': 'sarah@gnxsoft.com',
                'bio': 'Senior Technology Consultant with 15+ years in enterprise solutions'
            },
            {
                'name': 'Michael Chen',
                'email': 'michael@gnxsoft.com',
                'bio': 'Cloud Architecture Specialist and DevOps Expert'
            },
            {
                'name': 'Emily Rodriguez',
                'email': 'emily@gnxsoft.com',
                'bio': 'API Integration and System Integration Lead'
            },
            {
                'name': 'David Thompson',
                'email': 'david@gnxsoft.com',
                'bio': 'Digital Transformation and Business Intelligence Consultant'
            }
        ]

        authors = {}
        for author_data in authors_data:
            author = BlogAuthor.objects.create(**author_data)
            authors[author.name] = author
            self.stdout.write(f'Created author: {author.name}')

        # Create Categories
        categories_data = [
            {
                'title': 'Enterprise Software',
                'slug': 'enterprise-software',
                'description': 'Articles about enterprise software development and architecture',
                'display_order': 1
            },
            {
                'title': 'Digital Transformation',
                'slug': 'digital-transformation',
                'description': 'Insights on digital transformation strategies',
                'display_order': 2
            },
            {
                'title': 'System Integration',
                'slug': 'system-integration',
                'description': 'Best practices for system and API integration',
                'display_order': 3
            },
            {
                'title': 'Cloud Solutions',
                'slug': 'cloud-solutions',
                'description': 'Cloud computing and migration strategies',
                'display_order': 4
            },
            {
                'title': 'Security',
                'slug': 'security',
                'description': 'Enterprise security and cybersecurity topics',
                'display_order': 5
            },
            {
                'title': 'API Development',
                'slug': 'api-development',
                'description': 'API design, development, and management',
                'display_order': 6
            }
        ]

        categories = {}
        for cat_data in categories_data:
            category = BlogCategory.objects.create(**cat_data)
            categories[category.slug] = category
            self.stdout.write(f'Created category: {category.title}')

        # Create Tags
        tags_data = [
            'API', 'REST', 'GraphQL', 'Microservices', 'Cloud', 'AWS', 'Azure',
            'Security', 'DevOps', 'CI/CD', 'Docker', 'Kubernetes',
            'Enterprise', 'Integration', 'Architecture', 'Best Practices'
        ]

        tags = {}
        for tag_name in tags_data:
            tag = BlogTag.objects.create(name=tag_name)
            tags[tag_name] = tag
            self.stdout.write(f'Created tag: {tag.name}')

        # Create Blog Posts
        posts_data = [
            {
                'title': 'The Future of Enterprise Software Architecture',
                'content': '''
<h2>Introduction</h2>
<p>Enterprise software architecture is evolving rapidly. In this comprehensive guide, we explore the latest trends and best practices that are shaping the future of enterprise systems.</p>

<h3>Microservices and Modularity</h3>
<p>The shift towards microservices architecture has revolutionized how we build enterprise applications. By breaking down monolithic applications into smaller, independent services, organizations can achieve greater flexibility, scalability, and maintainability.</p>

<h3>Cloud-Native Development</h3>
<p>Cloud-native architecture is becoming the standard for modern enterprise applications. This approach leverages cloud computing capabilities to build and run scalable applications in dynamic environments.</p>

<h3>API-First Design</h3>
<p>API-first development ensures that applications are built with integration in mind from the start. This approach facilitates better communication between services and makes it easier to integrate with third-party systems.</p>

<h2>Best Practices</h2>
<ul>
<li>Design for scalability from the ground up</li>
<li>Implement robust security measures at every layer</li>
<li>Use containerization for consistent deployment</li>
<li>Adopt continuous integration and deployment practices</li>
<li>Monitor and optimize performance continuously</li>
</ul>

<h2>Conclusion</h2>
<p>The future of enterprise software architecture lies in flexibility, scalability, and cloud-native approaches. Organizations that embrace these principles will be better positioned to adapt to changing business needs.</p>
                ''',
                'excerpt': 'Exploring the latest trends in enterprise software architecture, from microservices to cloud-native development.',
                'author': authors['Sarah Johnson'],
                'category': categories['enterprise-software'],
                'tags': ['Enterprise', 'Architecture', 'Microservices', 'Cloud'],
                'thumbnail_url': '/images/blog/one.png',
                'featured': True,
                'reading_time': 8,
                'days_ago': 5
            },
            {
                'title': 'Digital Transformation Strategies for Large Enterprises',
                'content': '''
<h2>Understanding Digital Transformation</h2>
<p>Digital transformation is more than just adopting new technologies—it's about fundamentally changing how your organization operates and delivers value to customers.</p>

<h3>Key Components of Successful Transformation</h3>
<p>A successful digital transformation strategy must address technology, processes, and culture simultaneously. Organizations that focus on only one aspect often struggle to achieve their goals.</p>

<h3>Technology Stack Modernization</h3>
<p>Legacy systems can hold organizations back. Modernizing your technology stack is often the first step in digital transformation, enabling new capabilities and improving efficiency.</p>

<h2>Implementation Strategy</h2>
<ol>
<li>Assess current state and define vision</li>
<li>Identify quick wins and long-term goals</li>
<li>Build cross-functional transformation teams</li>
<li>Implement in phases with measurable milestones</li>
<li>Continuously gather feedback and adjust</li>
</ol>

<h2>Overcoming Challenges</h2>
<p>Common challenges include resistance to change, budget constraints, and technical debt. Success requires strong leadership commitment and clear communication throughout the organization.</p>
                ''',
                'excerpt': 'A comprehensive guide to digital transformation strategies tailored for large enterprise organizations.',
                'author': authors['David Thompson'],
                'category': categories['digital-transformation'],
                'tags': ['Digital Transformation', 'Enterprise', 'Best Practices'],
                'thumbnail_url': '/images/blog/two.png',
                'featured': True,
                'reading_time': 10,
                'days_ago': 8
            },
            {
                'title': 'API-First Approach to System Integration',
                'content': '''
<h2>What is API-First Development?</h2>
<p>API-first development is a strategy where APIs are treated as first-class citizens in the development process. Instead of being an afterthought, APIs are designed and built before any other code.</p>

<h3>Benefits of API-First Approach</h3>
<p>This approach offers numerous advantages including better developer experience, faster time to market, and improved system integration capabilities.</p>

<h3>RESTful API Design Principles</h3>
<p>RESTful APIs follow specific architectural principles that make them scalable, maintainable, and easy to understand. Key principles include statelessness, resource-based URLs, and standard HTTP methods.</p>

<h2>Best Practices</h2>
<ul>
<li>Design APIs with clear and consistent naming conventions</li>
<li>Version your APIs from the start</li>
<li>Implement proper authentication and authorization</li>
<li>Provide comprehensive documentation</li>
<li>Use appropriate HTTP status codes</li>
<li>Implement rate limiting and throttling</li>
</ul>

<h3>GraphQL vs REST</h3>
<p>While REST has been the standard for many years, GraphQL offers an alternative approach that can be more efficient for certain use cases. Understanding when to use each is crucial for effective API design.</p>
                ''',
                'excerpt': 'Learn how an API-first approach can streamline system integration and improve your software architecture.',
                'author': authors['Emily Rodriguez'],
                'category': categories['system-integration'],
                'tags': ['API', 'REST', 'GraphQL', 'Integration'],
                'thumbnail_url': '/images/blog/three.png',
                'reading_time': 7,
                'days_ago': 12
            },
            {
                'title': 'Cloud Migration Best Practices for Enterprise',
                'content': '''
<h2>Planning Your Cloud Migration</h2>
<p>Cloud migration is a complex process that requires careful planning and execution. A well-thought-out strategy can mean the difference between success and costly setbacks.</p>

<h3>Assessing Your Current Infrastructure</h3>
<p>Before migrating to the cloud, it's essential to thoroughly understand your current infrastructure, dependencies, and workload requirements.</p>

<h3>Choosing the Right Cloud Provider</h3>
<p>AWS, Azure, and Google Cloud each offer unique strengths. The right choice depends on your specific requirements, existing technology stack, and business objectives.</p>

<h2>Migration Strategies</h2>
<ol>
<li><strong>Lift and Shift:</strong> Move applications as-is to the cloud</li>
<li><strong>Replatform:</strong> Make minor optimizations during migration</li>
<li><strong>Refactor:</strong> Redesign applications to be cloud-native</li>
<li><strong>Rebuild:</strong> Completely rewrite applications for the cloud</li>
</ol>

<h3>Security Considerations</h3>
<p>Security should be a top priority during cloud migration. Implement encryption, access controls, and monitoring from day one.</p>

<h2>Post-Migration Optimization</h2>
<p>Migration is just the beginning. Continuous optimization of costs, performance, and security is essential for maximizing cloud benefits.</p>
                ''',
                'excerpt': 'Essential best practices and strategies for successfully migrating enterprise applications to the cloud.',
                'author': authors['Michael Chen'],
                'category': categories['cloud-solutions'],
                'tags': ['Cloud', 'AWS', 'Azure', 'Migration'],
                'thumbnail_url': '/images/blog/four.png',
                'featured': False,
                'reading_time': 9,
                'days_ago': 15
            },
            {
                'title': 'Enterprise Security in the Digital Age',
                'content': '''
<h2>The Evolving Security Landscape</h2>
<p>As enterprises embrace digital transformation, security challenges have become more complex. Organizations must adopt a comprehensive approach to protect their assets and data.</p>

<h3>Zero Trust Architecture</h3>
<p>Zero Trust is a security model that assumes no user or system should be trusted by default, even if they're inside the network perimeter.</p>

<h3>Multi-Factor Authentication</h3>
<p>MFA is no longer optional for enterprise security. Implementing strong authentication mechanisms is critical for protecting sensitive data and systems.</p>

<h2>Common Security Threats</h2>
<ul>
<li>Phishing and social engineering attacks</li>
<li>Ransomware and malware</li>
<li>Insider threats</li>
<li>DDoS attacks</li>
<li>API vulnerabilities</li>
</ul>

<h3>Implementing a Security-First Culture</h3>
<p>Technology alone cannot protect an organization. Security awareness training and a culture of security consciousness are equally important.</p>

<h2>Compliance and Regulations</h2>
<p>Understanding and adhering to regulations like GDPR, HIPAA, and SOC 2 is essential for enterprise organizations operating in regulated industries.</p>
                ''',
                'excerpt': 'Understanding modern security challenges and implementing robust security measures for enterprise environments.',
                'author': authors['Sarah Johnson'],
                'category': categories['security'],
                'tags': ['Security', 'Enterprise', 'Best Practices'],
                'thumbnail_url': '/images/blog/five.png',
                'reading_time': 6,
                'days_ago': 18
            },
            {
                'title': 'Building Scalable API Architectures',
                'content': '''
<h2>Scalability Fundamentals</h2>
<p>Building APIs that can scale to millions of requests requires careful architectural planning and implementation of proven patterns.</p>

<h3>Horizontal vs Vertical Scaling</h3>
<p>Understanding the difference between horizontal and vertical scaling is crucial for building scalable systems. Most modern APIs benefit from horizontal scaling strategies.</p>

<h3>Caching Strategies</h3>
<p>Implementing effective caching can dramatically improve API performance and reduce load on backend systems. Learn about different caching layers and when to use them.</p>

<h2>Performance Optimization</h2>
<ul>
<li>Database query optimization</li>
<li>Connection pooling</li>
<li>Asynchronous processing</li>
<li>Load balancing</li>
<li>CDN integration</li>
</ul>

<h3>Monitoring and Observability</h3>
<p>You can't optimize what you can't measure. Implementing comprehensive monitoring and logging is essential for maintaining scalable APIs.</p>

<h2>Rate Limiting and Throttling</h2>
<p>Protecting your API from abuse and ensuring fair usage requires implementing rate limiting and throttling mechanisms.</p>
                ''',
                'excerpt': 'Learn the principles and patterns for building API architectures that can scale to meet growing demands.',
                'author': authors['Emily Rodriguez'],
                'category': categories['api-development'],
                'tags': ['API', 'Architecture', 'Best Practices'],
                'thumbnail_url': '/images/blog/six.png',
                'reading_time': 8,
                'days_ago': 22
            },
            {
                'title': 'Microservices Architecture for Enterprise Applications',
                'content': '''
<h2>Understanding Microservices</h2>
<p>Microservices architecture has become the de facto standard for building scalable, maintainable enterprise applications. This architectural style structures an application as a collection of loosely coupled services.</p>

<h3>Key Characteristics</h3>
<p>Microservices are independently deployable, organized around business capabilities, and can be written in different programming languages.</p>

<h3>Service Communication Patterns</h3>
<p>Understanding different communication patterns between microservices is crucial. Options include synchronous REST APIs, message queues, and event-driven architectures.</p>

<h2>Design Patterns</h2>
<ol>
<li>API Gateway Pattern</li>
<li>Service Discovery</li>
<li>Circuit Breaker</li>
<li>Event Sourcing</li>
<li>CQRS (Command Query Responsibility Segregation)</li>
</ol>

<h3>Containerization with Docker</h3>
<p>Docker containers provide the perfect deployment vehicle for microservices, ensuring consistency across development and production environments.</p>

<h2>Challenges and Solutions</h2>
<p>While microservices offer many benefits, they also introduce complexity in areas like distributed transactions, data consistency, and service orchestration.</p>
                ''',
                'excerpt': 'A deep dive into microservices architecture patterns and best practices for enterprise applications.',
                'author': authors['Michael Chen'],
                'category': categories['enterprise-software'],
                'tags': ['Microservices', 'Architecture', 'Docker', 'Kubernetes'],
                'thumbnail_url': '/images/blog/seven.png',
                'featured': True,
                'reading_time': 11,
                'days_ago': 25
            },
            {
                'title': 'Data Analytics and Business Intelligence Solutions',
                'content': '''
<h2>The Power of Data-Driven Decisions</h2>
<p>In today's business environment, data analytics and business intelligence are no longer optional—they're essential for staying competitive.</p>

<h3>Modern BI Tools and Platforms</h3>
<p>Modern BI platforms offer self-service analytics, real-time dashboards, and AI-powered insights that democratize data access across the organization.</p>

<h3>Building a Data Warehouse</h3>
<p>A well-designed data warehouse serves as the foundation for business intelligence initiatives, providing a single source of truth for organizational data.</p>

<h2>Analytics Maturity Model</h2>
<ol>
<li>Descriptive Analytics - What happened?</li>
<li>Diagnostic Analytics - Why did it happen?</li>
<li>Predictive Analytics - What will happen?</li>
<li>Prescriptive Analytics - What should we do?</li>
</ol>

<h3>Real-Time Analytics</h3>
<p>The ability to analyze data in real-time enables organizations to respond quickly to changing conditions and make timely decisions.</p>

<h2>Data Governance and Quality</h2>
<p>Without proper data governance and quality management, analytics initiatives can produce unreliable results. Establishing data quality standards is crucial.</p>

<h3>Machine Learning Integration</h3>
<p>Integrating machine learning models into BI platforms can provide deeper insights and enable predictive capabilities.</p>
                ''',
                'excerpt': 'Leveraging data analytics and business intelligence to drive informed decision-making in enterprise environments.',
                'author': authors['David Thompson'],
                'category': categories['digital-transformation'],
                'tags': ['Analytics', 'BI', 'Enterprise', 'Best Practices'],
                'thumbnail_url': '/images/blog/eight.png',
                'reading_time': 9,
                'days_ago': 30
            }
        ]

        # Create posts
        for post_data in posts_data:
            tag_names = post_data.pop('tags')
            days_ago = post_data.pop('days_ago')
            
            post = BlogPost.objects.create(
                **post_data,
                published_at=timezone.now() - timedelta(days=days_ago)
            )
            
            # Add tags
            for tag_name in tag_names:
                if tag_name in tags:
                    post.tags.add(tags[tag_name])
            
            self.stdout.write(f'Created post: {post.title}')

        self.stdout.write(self.style.SUCCESS('\nSuccessfully populated blog data!'))
        self.stdout.write(f'Created {BlogAuthor.objects.count()} authors')
        self.stdout.write(f'Created {BlogCategory.objects.count()} categories')
        self.stdout.write(f'Created {BlogTag.objects.count()} tags')
        self.stdout.write(f'Created {BlogPost.objects.count()} blog posts')

