from django.core.management.base import BaseCommand
from django.utils.text import slugify
from django.db import transaction
from support.models import (
    TicketStatus, TicketPriority, TicketCategory,
    KnowledgeBaseCategory, KnowledgeBaseArticle
)
from services.models import Service


class Command(BaseCommand):
    help = 'Populate support center with enterprise support data based on services'

    def add_arguments(self, parser):
        parser.add_argument(
            '--delete-old',
            action='store_true',
            help='Delete all existing support data before populating',
        )

    def handle(self, *args, **kwargs):
        delete_old = kwargs.get('delete_old', False)
        
        self.stdout.write(self.style.SUCCESS('Starting to populate enterprise support data...'))

        with transaction.atomic():
            # Delete old data if requested
            if delete_old:
                self.delete_old_data()
            
            # Create Ticket Statuses
            self.create_ticket_statuses()
            
            # Create Ticket Priorities
            self.create_ticket_priorities()
            
            # Create Ticket Categories based on services
            self.create_ticket_categories()
            
            # Create Knowledge Base Categories
            self.create_kb_categories()
            
            # Create Knowledge Base Articles
            self.create_kb_articles()

        self.stdout.write(self.style.SUCCESS('Successfully populated enterprise support data!'))

    def delete_old_data(self):
        """Delete all existing support data"""
        self.stdout.write(self.style.WARNING('Deleting old support data...'))
        
        # Delete in reverse order of dependencies
        kb_articles_count = KnowledgeBaseArticle.objects.count()
        KnowledgeBaseArticle.objects.all().delete()
        self.stdout.write(f'  ✓ Deleted {kb_articles_count} knowledge base articles')
        
        kb_categories_count = KnowledgeBaseCategory.objects.count()
        KnowledgeBaseCategory.objects.all().delete()
        self.stdout.write(f'  ✓ Deleted {kb_categories_count} knowledge base categories')
        
        ticket_categories_count = TicketCategory.objects.count()
        TicketCategory.objects.all().delete()
        self.stdout.write(f'  ✓ Deleted {ticket_categories_count} ticket categories')
        
        ticket_priorities_count = TicketPriority.objects.count()
        TicketPriority.objects.all().delete()
        self.stdout.write(f'  ✓ Deleted {ticket_priorities_count} ticket priorities')
        
        ticket_statuses_count = TicketStatus.objects.count()
        TicketStatus.objects.all().delete()
        self.stdout.write(f'  ✓ Deleted {ticket_statuses_count} ticket statuses')
        
        self.stdout.write(self.style.SUCCESS('Old data deleted successfully!'))

    def create_ticket_statuses(self):
        self.stdout.write('Creating ticket statuses...')
        
        statuses = [
            {'name': 'Open', 'color': '#3b82f6', 'description': 'Ticket has been opened and is awaiting assignment', 'is_closed': False, 'display_order': 1},
            {'name': 'In Progress', 'color': '#f59e0b', 'description': 'Ticket is being actively worked on by support team', 'is_closed': False, 'display_order': 2},
            {'name': 'Pending Response', 'color': '#8b5cf6', 'description': 'Waiting for customer response or additional information', 'is_closed': False, 'display_order': 3},
            {'name': 'On Hold', 'color': '#6b7280', 'description': 'Ticket is temporarily on hold', 'is_closed': False, 'display_order': 4},
            {'name': 'Resolved', 'color': '#10b981', 'description': 'Ticket has been resolved and is awaiting customer confirmation', 'is_closed': True, 'display_order': 5},
            {'name': 'Closed', 'color': '#6b7280', 'description': 'Ticket has been closed', 'is_closed': True, 'display_order': 6},
        ]

        for status_data in statuses:
            status, created = TicketStatus.objects.get_or_create(
                name=status_data['name'],
                defaults=status_data
            )
            if created:
                self.stdout.write(self.style.SUCCESS(f'  ✓ Created status: {status.name}'))
            else:
                self.stdout.write(f'  - Status already exists: {status.name}')

    def create_ticket_priorities(self):
        self.stdout.write('Creating ticket priorities...')
        
        priorities = [
            {'name': 'Low', 'level': 4, 'color': '#6b7280', 'description': 'Low priority issue - non-urgent', 'sla_hours': 72},
            {'name': 'Medium', 'level': 3, 'color': '#3b82f6', 'description': 'Medium priority issue - standard response', 'sla_hours': 48},
            {'name': 'High', 'level': 2, 'color': '#f59e0b', 'description': 'High priority issue - requires prompt attention', 'sla_hours': 24},
            {'name': 'Critical', 'level': 1, 'color': '#ef4444', 'description': 'Critical issue requiring immediate attention - production down', 'sla_hours': 4},
        ]

        for priority_data in priorities:
            priority, created = TicketPriority.objects.get_or_create(
                name=priority_data['name'],
                defaults=priority_data
            )
            if created:
                self.stdout.write(self.style.SUCCESS(f'  ✓ Created priority: {priority.name}'))
            else:
                self.stdout.write(f'  - Priority already exists: {priority.name}')

    def create_ticket_categories(self):
        self.stdout.write('Creating ticket categories based on services...')
        
        # Get all active services
        services = Service.objects.filter(is_active=True).order_by('display_order')
        
        # Service-based categories with icons and colors
        service_category_mapping = {
            'backend': {'icon': 'fa-server', 'color': '#3b82f6', 'description': 'Backend development, APIs, and server-side issues'},
            'frontend': {'icon': 'fa-code', 'color': '#10b981', 'description': 'Frontend development, UI/UX, and client-side issues'},
            'data': {'icon': 'fa-database', 'color': '#8b5cf6', 'description': 'Data replication, synchronization, and database issues'},
            'infrastructure': {'icon': 'fa-cloud', 'color': '#f59e0b', 'description': 'Infrastructure management, cloud services, and system administration'},
            'server': {'icon': 'fa-server', 'color': '#ef4444', 'description': 'Server management, configuration, and administration'},
            'devops': {'icon': 'fa-cogs', 'color': '#06b6d4', 'description': 'DevOps, CI/CD, automation, and deployment issues'},
            'api': {'icon': 'fa-plug', 'color': '#ec4899', 'description': 'API integration, connectivity, and third-party service issues'},
            'ai': {'icon': 'fa-brain', 'color': '#daa520', 'description': 'AI/ML solutions, model training, and machine learning issues'},
        }
        
        # Base categories that apply to all services
        base_categories = [
            {'name': 'Technical Support', 'description': 'General technical issues and troubleshooting', 'color': '#3b82f6', 'icon': 'fa-wrench', 'display_order': 1},
            {'name': 'Billing & Payments', 'description': 'Billing questions and payment issues', 'color': '#10b981', 'icon': 'fa-credit-card', 'display_order': 2},
            {'name': 'Account Management', 'description': 'Account settings and access issues', 'color': '#8b5cf6', 'icon': 'fa-user-cog', 'display_order': 3},
            {'name': 'Feature Requests', 'description': 'Request new features or improvements', 'color': '#06b6d4', 'icon': 'fa-lightbulb', 'display_order': 4},
            {'name': 'Bug Reports', 'description': 'Report software bugs and issues', 'color': '#ef4444', 'icon': 'fa-bug', 'display_order': 5},
        ]
        
        # Create base categories
        display_order = 1
        for category_data in base_categories:
            category, created = TicketCategory.objects.get_or_create(
                name=category_data['name'],
                defaults={**category_data, 'display_order': display_order}
            )
            if created:
                self.stdout.write(self.style.SUCCESS(f'  ✓ Created category: {category.name}'))
            else:
                self.stdout.write(f'  - Category already exists: {category.name}')
            display_order += 1
        
        # Create service-specific categories
        for service in services:
            service_title_lower = service.title.lower()
            category_name = None
            category_config = None
            
            # Map service to category
            if 'backend' in service_title_lower:
                category_name = f'{service.title} Support'
                category_config = service_category_mapping['backend']
            elif 'frontend' in service_title_lower:
                category_name = f'{service.title} Support'
                category_config = service_category_mapping['frontend']
            elif 'data replication' in service_title_lower or 'synchronization' in service_title_lower:
                category_name = f'{service.title} Support'
                category_config = service_category_mapping['data']
            elif 'infrastructure management' in service_title_lower or 'infrastructure support' in service_title_lower:
                category_name = f'{service.title} Support'
                category_config = service_category_mapping['infrastructure']
            elif 'server management' in service_title_lower or 'server administration' in service_title_lower:
                category_name = f'{service.title} Support'
                category_config = service_category_mapping['server']
            elif 'devops' in service_title_lower or 'automation' in service_title_lower:
                category_name = f'{service.title} Support'
                category_config = service_category_mapping['devops']
            elif 'api integration' in service_title_lower:
                category_name = f'{service.title} Support'
                category_config = service_category_mapping['api']
            elif 'artificial intelligence' in service_title_lower or 'machine learning' in service_title_lower or 'ai' in service_title_lower:
                category_name = f'{service.title} Support'
                category_config = service_category_mapping['ai']
            
            if category_name and category_config:
                category, created = TicketCategory.objects.get_or_create(
                    name=category_name,
                    defaults={
                        'description': f'Support for {service.title}. {category_config["description"]}',
                        'color': category_config['color'],
                        'icon': category_config['icon'],
                        'display_order': display_order
                    }
                )
                if created:
                    self.stdout.write(self.style.SUCCESS(f'  ✓ Created category: {category.name}'))
                else:
                    self.stdout.write(f'  - Category already exists: {category.name}')
                display_order += 1

    def create_kb_categories(self):
        self.stdout.write('Creating knowledge base categories...')
        
        categories = [
            {'name': 'Getting Started', 'slug': 'getting-started', 'description': 'Learn the basics and get started with our enterprise services', 'icon': 'fa-rocket', 'color': '#3b82f6', 'display_order': 1},
            {'name': 'Backend Development', 'slug': 'backend-development', 'description': 'Backend development guides, APIs, and server-side documentation', 'icon': 'fa-server', 'color': '#3b82f6', 'display_order': 2},
            {'name': 'Frontend Development', 'slug': 'frontend-development', 'description': 'Frontend development guides, UI/UX, and client-side documentation', 'icon': 'fa-code', 'color': '#10b981', 'display_order': 3},
            {'name': 'Infrastructure & DevOps', 'slug': 'infrastructure-devops', 'description': 'Infrastructure management, DevOps, and deployment guides', 'icon': 'fa-cloud', 'color': '#f59e0b', 'display_order': 4},
            {'name': 'Data Management', 'slug': 'data-management', 'description': 'Data replication, synchronization, and database management', 'icon': 'fa-database', 'color': '#8b5cf6', 'display_order': 5},
            {'name': 'API Integration', 'slug': 'api-integration', 'description': 'API integration guides and third-party service connectivity', 'icon': 'fa-plug', 'color': '#ec4899', 'display_order': 6},
            {'name': 'AI & Machine Learning', 'slug': 'ai-machine-learning', 'description': 'AI/ML solutions, model training, and machine learning guides', 'icon': 'fa-brain', 'color': '#daa520', 'display_order': 7},
            {'name': 'Troubleshooting', 'slug': 'troubleshooting', 'description': 'Common issues and how to resolve them', 'icon': 'fa-tools', 'color': '#ef4444', 'display_order': 8},
            {'name': 'Security & Privacy', 'slug': 'security-privacy', 'description': 'Security features, best practices, and privacy settings', 'icon': 'fa-shield-alt', 'color': '#ef4444', 'display_order': 9},
            {'name': 'Account & Billing', 'slug': 'account-billing', 'description': 'Manage your account and billing information', 'icon': 'fa-user-circle', 'color': '#10b981', 'display_order': 10},
            {'name': 'Best Practices', 'slug': 'best-practices', 'description': 'Tips and best practices for optimal use of our services', 'icon': 'fa-star', 'color': '#daa520', 'display_order': 11},
        ]

        for category_data in categories:
            category, created = KnowledgeBaseCategory.objects.get_or_create(
                slug=category_data['slug'],
                defaults=category_data
            )
            if created:
                self.stdout.write(self.style.SUCCESS(f'  ✓ Created KB category: {category.name}'))
            else:
                self.stdout.write(f'  - KB category already exists: {category.name}')

    def create_kb_articles(self):
        self.stdout.write('Creating knowledge base articles...')
        
        # Get categories
        getting_started = KnowledgeBaseCategory.objects.filter(slug='getting-started').first()
        backend_dev = KnowledgeBaseCategory.objects.filter(slug='backend-development').first()
        frontend_dev = KnowledgeBaseCategory.objects.filter(slug='frontend-development').first()
        infrastructure = KnowledgeBaseCategory.objects.filter(slug='infrastructure-devops').first()
        data_mgmt = KnowledgeBaseCategory.objects.filter(slug='data-management').first()
        api_integration = KnowledgeBaseCategory.objects.filter(slug='api-integration').first()
        ai_ml = KnowledgeBaseCategory.objects.filter(slug='ai-machine-learning').first()
        troubleshooting = KnowledgeBaseCategory.objects.filter(slug='troubleshooting').first()
        security = KnowledgeBaseCategory.objects.filter(slug='security-privacy').first()
        account_billing = KnowledgeBaseCategory.objects.filter(slug='account-billing').first()
        best_practices = KnowledgeBaseCategory.objects.filter(slug='best-practices').first()

        articles = [
            {
                'title': 'Getting Started with Enterprise Services',
                'slug': 'getting-started-enterprise-services',
                'category': getting_started,
                'summary': 'A comprehensive guide to help you get started with our enterprise services quickly and efficiently.',
                'content': '''<h2>Welcome to GNX Enterprise Services!</h2>
                <p>This guide will help you get started with our enterprise services in just a few simple steps.</p>
                
                <h3>Step 1: Understand Your Service Package</h3>
                <p>Review your service agreement and understand what services are included in your package. Each service comes with specific deliverables, timelines, and support options.</p>
                
                <h3>Step 2: Access Your Service Portal</h3>
                <p>Log in to your enterprise portal to access service documentation, support tickets, and project management tools.</p>
                
                <h3>Step 3: Set Up Your Development Environment</h3>
                <p>Follow the setup guides for your specific services. We provide detailed documentation for backend, frontend, infrastructure, and integration services.</p>
                
                <h3>Step 4: Connect with Your Support Team</h3>
                <p>Your dedicated support team is available 24/7. Use the support ticket system for technical issues or contact your account manager for service-related questions.</p>
                
                <h3>Step 5: Explore Knowledge Base</h3>
                <p>Browse our comprehensive knowledge base for detailed guides, API documentation, troubleshooting tips, and best practices.</p>
                
                <p>If you need any help, our enterprise support team is always here to assist you!</p>''',
                'is_published': True,
                'is_featured': True,
            },
            {
                'title': 'Enterprise Backend Development Best Practices',
                'slug': 'backend-development-best-practices',
                'category': backend_dev,
                'summary': 'Learn best practices for enterprise backend development including API design, database optimization, and security.',
                'content': '''<h2>Backend Development Best Practices</h2>
                <p>Follow these best practices to ensure your backend applications are robust, scalable, and secure.</p>
                
                <h3>API Design Principles</h3>
                <ul>
                    <li>Use RESTful conventions for API endpoints</li>
                    <li>Implement proper versioning (e.g., /api/v1/)</li>
                    <li>Use consistent naming conventions</li>
                    <li>Return appropriate HTTP status codes</li>
                    <li>Implement pagination for large datasets</li>
                </ul>
                
                <h3>Database Optimization</h3>
                <ul>
                    <li>Use proper indexing for frequently queried fields</li>
                    <li>Implement connection pooling</li>
                    <li>Use database transactions appropriately</li>
                    <li>Optimize queries to avoid N+1 problems</li>
                    <li>Implement caching strategies</li>
                </ul>
                
                <h3>Security Best Practices</h3>
                <ul>
                    <li>Implement authentication and authorization</li>
                    <li>Use HTTPS for all API communications</li>
                    <li>Validate and sanitize all inputs</li>
                    <li>Implement rate limiting</li>
                    <li>Keep dependencies updated</li>
                </ul>
                
                <h3>Performance Optimization</h3>
                <ul>
                    <li>Implement caching at multiple levels</li>
                    <li>Use async processing for long-running tasks</li>
                    <li>Optimize database queries</li>
                    <li>Implement proper logging and monitoring</li>
                    <li>Use CDN for static assets</li>
                </ul>''',
                'is_published': True,
                'is_featured': True,
            },
            {
                'title': 'Frontend Development Guidelines',
                'slug': 'frontend-development-guidelines',
                'category': frontend_dev,
                'summary': 'Comprehensive guidelines for building modern, responsive frontend applications.',
                'content': '''<h2>Frontend Development Guidelines</h2>
                <p>Build modern, performant, and accessible frontend applications with these guidelines.</p>
                
                <h3>Component Architecture</h3>
                <ul>
                    <li>Use component-based architecture (React, Vue, etc.)</li>
                    <li>Keep components small and focused</li>
                    <li>Implement proper state management</li>
                    <li>Use reusable component libraries</li>
                    <li>Follow consistent naming conventions</li>
                </ul>
                
                <h3>Performance Optimization</h3>
                <ul>
                    <li>Implement code splitting and lazy loading</li>
                    <li>Optimize images and assets</li>
                    <li>Use efficient rendering techniques</li>
                    <li>Minimize bundle size</li>
                    <li>Implement proper caching strategies</li>
                </ul>
                
                <h3>Responsive Design</h3>
                <ul>
                    <li>Use mobile-first approach</li>
                    <li>Test on multiple devices and browsers</li>
                    <li>Implement flexible layouts</li>
                    <li>Optimize touch interactions</li>
                    <li>Ensure proper viewport settings</li>
                </ul>
                
                <h3>Accessibility</h3>
                <ul>
                    <li>Use semantic HTML</li>
                    <li>Implement proper ARIA labels</li>
                    <li>Ensure keyboard navigation</li>
                    <li>Maintain proper color contrast</li>
                    <li>Test with screen readers</li>
                </ul>''',
                'is_published': True,
                'is_featured': True,
            },
            {
                'title': 'DevOps and Infrastructure Setup Guide',
                'slug': 'devops-infrastructure-setup',
                'category': infrastructure,
                'summary': 'Complete guide to setting up DevOps pipelines and infrastructure automation.',
                'content': '''<h2>DevOps and Infrastructure Setup</h2>
                <p>Set up robust DevOps pipelines and infrastructure automation for your enterprise applications.</p>
                
                <h3>CI/CD Pipeline Setup</h3>
                <ul>
                    <li>Configure automated testing in your pipeline</li>
                    <li>Implement code quality checks</li>
                    <li>Set up automated deployments</li>
                    <li>Configure environment-specific deployments</li>
                    <li>Implement rollback strategies</li>
                </ul>
                
                <h3>Infrastructure as Code</h3>
                <ul>
                    <li>Use Terraform or CloudFormation for infrastructure</li>
                    <li>Version control your infrastructure code</li>
                    <li>Implement infrastructure testing</li>
                    <li>Use configuration management tools</li>
                    <li>Document infrastructure changes</li>
                </ul>
                
                <h3>Containerization</h3>
                <ul>
                    <li>Containerize your applications with Docker</li>
                    <li>Use Kubernetes for orchestration</li>
                    <li>Implement proper health checks</li>
                    <li>Configure resource limits</li>
                    <li>Set up container registries</li>
                </ul>
                
                <h3>Monitoring and Logging</h3>
                <ul>
                    <li>Implement comprehensive monitoring</li>
                    <li>Set up centralized logging</li>
                    <li>Configure alerting systems</li>
                    <li>Use APM tools for performance monitoring</li>
                    <li>Implement log aggregation</li>
                </ul>''',
                'is_published': True,
                'is_featured': True,
            },
            {
                'title': 'Data Replication and Synchronization Guide',
                'slug': 'data-replication-synchronization',
                'category': data_mgmt,
                'summary': 'Complete guide to setting up and managing data replication and synchronization.',
                'content': '''<h2>Data Replication and Synchronization</h2>
                <p>Ensure data consistency and availability with proper replication and synchronization strategies.</p>
                
                <h3>Replication Strategies</h3>
                <ul>
                    <li>Master-Slave replication for read scaling</li>
                    <li>Master-Master replication for high availability</li>
                    <li>Multi-region replication for disaster recovery</li>
                    <li>Real-time vs. batch replication</li>
                    <li>Conflict resolution strategies</li>
                </ul>
                
                <h3>Synchronization Best Practices</h3>
                <ul>
                    <li>Implement change data capture (CDC)</li>
                    <li>Use transaction logs for consistency</li>
                    <li>Monitor replication lag</li>
                    <li>Implement data validation</li>
                    <li>Set up automated failover</li>
                </ul>
                
                <h3>Disaster Recovery</h3>
                <ul>
                    <li>Regular backup schedules</li>
                    <li>Test recovery procedures</li>
                    <li>Maintain multiple backup copies</li>
                    <li>Document recovery processes</li>
                    <li>Monitor backup health</li>
                </ul>
                
                <h3>Troubleshooting Common Issues</h3>
                <ul>
                    <li>Replication lag issues</li>
                    <li>Data inconsistency problems</li>
                    <li>Network connectivity issues</li>
                    <li>Storage capacity management</li>
                    <li>Performance optimization</li>
                </ul>''',
                'is_published': True,
                'is_featured': False,
            },
            {
                'title': 'API Integration Best Practices',
                'slug': 'api-integration-best-practices',
                'category': api_integration,
                'summary': 'Best practices for integrating with third-party APIs and services.',
                'content': '''<h2>API Integration Best Practices</h2>
                <p>Integrate seamlessly with third-party APIs using these best practices.</p>
                
                <h3>Authentication and Security</h3>
                <ul>
                    <li>Use OAuth 2.0 for secure authentication</li>
                    <li>Store API keys securely</li>
                    <li>Implement token refresh mechanisms</li>
                    <li>Use HTTPS for all API calls</li>
                    <li>Validate API responses</li>
                </ul>
                
                <h3>Error Handling</h3>
                <ul>
                    <li>Implement retry logic with exponential backoff</li>
                    <li>Handle rate limiting gracefully</li>
                    <li>Log all API errors</li>
                    <li>Implement circuit breakers</li>
                    <li>Provide meaningful error messages</li>
                </ul>
                
                <h3>Performance Optimization</h3>
                <ul>
                    <li>Implement request caching</li>
                    <li>Use batch requests when possible</li>
                    <li>Implement connection pooling</li>
                    <li>Monitor API response times</li>
                    <li>Optimize payload sizes</li>
                </ul>
                
                <h3>Testing and Monitoring</h3>
                <ul>
                    <li>Test with sandbox environments</li>
                    <li>Monitor API usage and costs</li>
                    <li>Set up alerts for failures</li>
                    <li>Document integration patterns</li>
                    <li>Version your integrations</li>
                </ul>''',
                'is_published': True,
                'is_featured': False,
            },
            {
                'title': 'AI and Machine Learning Implementation Guide',
                'slug': 'ai-machine-learning-implementation',
                'category': ai_ml,
                'summary': 'Guide to implementing AI and machine learning solutions in your applications.',
                'content': '''<h2>AI and Machine Learning Implementation</h2>
                <p>Integrate AI and machine learning capabilities into your enterprise applications.</p>
                
                <h3>Model Development</h3>
                <ul>
                    <li>Define clear use cases and objectives</li>
                    <li>Prepare and clean your data</li>
                    <li>Choose appropriate algorithms</li>
                    <li>Train and validate models</li>
                    <li>Evaluate model performance</li>
                </ul>
                
                <h3>Model Deployment</h3>
                <ul>
                    <li>Containerize models for deployment</li>
                    <li>Implement model versioning</li>
                    <li>Set up model serving infrastructure</li>
                    <li>Implement A/B testing</li>
                    <li>Monitor model performance</li>
                </ul>
                
                <h3>Integration Best Practices</h3>
                <ul>
                    <li>Use API gateways for model access</li>
                    <li>Implement proper authentication</li>
                    <li>Handle model inference errors</li>
                    <li>Optimize inference latency</li>
                    <li>Implement caching strategies</li>
                </ul>
                
                <h3>Monitoring and Maintenance</h3>
                <ul>
                    <li>Monitor model accuracy over time</li>
                    <li>Track data drift</li>
                    <li>Implement model retraining pipelines</li>
                    <li>Set up performance alerts</li>
                    <li>Document model behavior</li>
                </ul>''',
                'is_published': True,
                'is_featured': True,
            },
            {
                'title': 'Common Troubleshooting Issues',
                'slug': 'common-troubleshooting-issues',
                'category': troubleshooting,
                'summary': 'Common issues and their solutions for enterprise services.',
                'content': '''<h2>Common Troubleshooting Issues</h2>
                <p>Resolve common issues quickly with these troubleshooting guides.</p>
                
                <h3>Connection Issues</h3>
                <ul>
                    <li>Check network connectivity</li>
                    <li>Verify firewall settings</li>
                    <li>Test DNS resolution</li>
                    <li>Check SSL/TLS certificates</li>
                    <li>Review connection timeouts</li>
                </ul>
                
                <h3>Performance Issues</h3>
                <ul>
                    <li>Check server resource usage</li>
                    <li>Review database query performance</li>
                    <li>Analyze application logs</li>
                    <li>Check for memory leaks</li>
                    <li>Review caching strategies</li>
                </ul>
                
                <h3>Authentication Problems</h3>
                <ul>
                    <li>Verify credentials</li>
                    <li>Check token expiration</li>
                    <li>Review permission settings</li>
                    <li>Test with different accounts</li>
                    <li>Check session management</li>
                </ul>
                
                <h3>Data Issues</h3>
                <ul>
                    <li>Verify data integrity</li>
                    <li>Check replication status</li>
                    <li>Review data validation rules</li>
                    <li>Check for data corruption</li>
                    <li>Verify backup integrity</li>
                </ul>
                
                <p>If you continue to experience issues, please contact our support team.</p>''',
                'is_published': True,
                'is_featured': False,
            },
            {
                'title': 'Enterprise Security Best Practices',
                'slug': 'enterprise-security-best-practices',
                'category': security,
                'summary': 'Essential security practices for enterprise applications and infrastructure.',
                'content': '''<h2>Enterprise Security Best Practices</h2>
                <p>Protect your enterprise applications and data with these security best practices.</p>
                
                <h3>Authentication and Authorization</h3>
                <ul>
                    <li>Implement multi-factor authentication (MFA)</li>
                    <li>Use strong password policies</li>
                    <li>Implement role-based access control (RBAC)</li>
                    <li>Regularly review user permissions</li>
                    <li>Use OAuth 2.0 for API authentication</li>
                </ul>
                
                <h3>Data Protection</h3>
                <ul>
                    <li>Encrypt data at rest and in transit</li>
                    <li>Implement proper key management</li>
                    <li>Use secure communication protocols</li>
                    <li>Implement data masking for sensitive information</li>
                    <li>Regularly backup critical data</li>
                </ul>
                
                <h3>Network Security</h3>
                <ul>
                    <li>Use firewalls and network segmentation</li>
                    <li>Implement DDoS protection</li>
                    <li>Use VPNs for remote access</li>
                    <li>Monitor network traffic</li>
                    <li>Implement intrusion detection systems</li>
                </ul>
                
                <h3>Compliance and Auditing</h3>
                <ul>
                    <li>Maintain security audit logs</li>
                    <li>Regularly review access logs</li>
                    <li>Conduct security assessments</li>
                    <li>Stay compliant with regulations</li>
                    <li>Document security procedures</li>
                </ul>''',
                'is_published': True,
                'is_featured': True,
            },
            {
                'title': 'Understanding Your Enterprise Billing',
                'slug': 'enterprise-billing-guide',
                'category': account_billing,
                'summary': 'Learn how enterprise billing works and how to manage your account.',
                'content': '''<h2>Enterprise Billing Guide</h2>
                <p>Understand your enterprise billing and manage your account effectively.</p>
                
                <h3>Billing Structure</h3>
                <ul>
                    <li>Service-based pricing models</li>
                    <li>Monthly vs. annual billing options</li>
                    <li>Usage-based charges</li>
                    <li>Support tier pricing</li>
                    <li>Additional service add-ons</li>
                </ul>
                
                <h3>Payment Methods</h3>
                <ul>
                    <li>Credit card payments</li>
                    <li>Bank transfers</li>
                    <li>Purchase orders</li>
                    <li>Invoice-based billing</li>
                    <li>Payment terms and schedules</li>
                </ul>
                
                <h3>Managing Your Account</h3>
                <ul>
                    <li>Update payment information</li>
                    <li>View billing history</li>
                    <li>Download invoices</li>
                    <li>Manage service subscriptions</li>
                    <li>Contact billing support</li>
                </ul>
                
                <h3>Billing Support</h3>
                <p>For billing questions or issues, contact our billing team through the support portal or email billing@gnxsoft.com.</p>''',
                'is_published': True,
                'is_featured': False,
            },
        ]

        for article_data in articles:
            if article_data['category']:
                article, created = KnowledgeBaseArticle.objects.get_or_create(
                    slug=article_data['slug'],
                    defaults=article_data
                )
                if created:
                    self.stdout.write(self.style.SUCCESS(f'  ✓ Created article: {article.title}'))
                else:
                    self.stdout.write(f'  - Article already exists: {article.title}')
