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


class Command(BaseCommand):
    help = 'Populate support center with initial data'

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

        # Create Ticket Statuses
        self.create_ticket_statuses()
        
        # Create Ticket Priorities
        self.create_ticket_priorities()
        
        # Create Ticket Categories
        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 support data!'))

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

        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', 'sla_hours': 72},
            {'name': 'Medium', 'level': 3, 'color': '#3b82f6', 'description': 'Medium priority issue', 'sla_hours': 48},
            {'name': 'High', 'level': 2, 'color': '#f59e0b', 'description': 'High priority issue', 'sla_hours': 24},
            {'name': 'Critical', 'level': 1, 'color': '#ef4444', 'description': 'Critical issue requiring immediate attention', '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...')
        
        categories = [
            {'name': 'Technical Support', 'description': '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': 'Product Inquiry', 'description': 'Questions about products and features', 'color': '#f59e0b', 'icon': 'fa-box', 'display_order': 4},
            {'name': 'Bug Reports', 'description': 'Report software bugs and issues', 'color': '#ef4444', 'icon': 'fa-bug', 'display_order': 5},
            {'name': 'Feature Requests', 'description': 'Request new features or improvements', 'color': '#06b6d4', 'icon': 'fa-lightbulb', 'display_order': 6},
        ]

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

    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 quickly', 'icon': 'fa-rocket', 'color': '#3b82f6', 'display_order': 1},
            {'name': 'Account & Billing', 'slug': 'account-billing', 'description': 'Manage your account and billing information', 'icon': 'fa-user-circle', 'color': '#10b981', 'display_order': 2},
            {'name': 'Technical Documentation', 'slug': 'technical-docs', 'description': 'Technical guides and API documentation', 'icon': 'fa-code', 'color': '#8b5cf6', 'display_order': 3},
            {'name': 'Troubleshooting', 'slug': 'troubleshooting', 'description': 'Common issues and how to resolve them', 'icon': 'fa-tools', 'color': '#f59e0b', 'display_order': 4},
            {'name': 'Security & Privacy', 'slug': 'security-privacy', 'description': 'Security features and privacy settings', 'icon': 'fa-shield-alt', 'color': '#ef4444', 'display_order': 5},
            {'name': 'Best Practices', 'slug': 'best-practices', 'description': 'Tips and best practices for optimal use', 'icon': 'fa-star', 'color': '#daa520', 'display_order': 6},
        ]

        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()
        account_billing = KnowledgeBaseCategory.objects.filter(slug='account-billing').first()
        technical = KnowledgeBaseCategory.objects.filter(slug='technical-docs').first()
        troubleshooting = KnowledgeBaseCategory.objects.filter(slug='troubleshooting').first()

        articles = [
            {
                'title': 'How to Get Started with Our Platform',
                'slug': 'how-to-get-started',
                'category': getting_started,
                'summary': 'A comprehensive guide to help you get started with our platform quickly and easily.',
                'content': '''<h2>Welcome to Our Platform!</h2>
                <p>This guide will help you get started with our platform in just a few simple steps.</p>
                
                <h3>Step 1: Create Your Account</h3>
                <p>Visit our sign-up page and create your account using your email address or social login.</p>
                
                <h3>Step 2: Complete Your Profile</h3>
                <p>Add your company information and customize your profile settings.</p>
                
                <h3>Step 3: Explore the Dashboard</h3>
                <p>Familiarize yourself with the main dashboard and available features.</p>
                
                <h3>Step 4: Start Using Our Services</h3>
                <p>Begin using our services and tools to achieve your business goals.</p>
                
                <p>If you need any help, our support team is always here to assist you!</p>''',
                'is_published': True,
                'is_featured': True,
            },
            {
                'title': 'Understanding Your Billing Cycle',
                'slug': 'understanding-billing-cycle',
                'category': account_billing,
                'summary': 'Learn how our billing cycle works and how to manage your payments.',
                'content': '''<h2>Billing Cycle Overview</h2>
                <p>Understanding your billing cycle is important for managing your subscription effectively.</p>
                
                <h3>Monthly Billing</h3>
                <p>For monthly subscriptions, you'll be charged on the same date each month.</p>
                
                <h3>Annual Billing</h3>
                <p>Annual subscriptions offer a discount and are billed once per year.</p>
                
                <h3>Managing Your Subscription</h3>
                <p>You can upgrade, downgrade, or cancel your subscription at any time from your account settings.</p>''',
                'is_published': True,
                'is_featured': True,
            },
            {
                'title': 'API Documentation Overview',
                'slug': 'api-documentation-overview',
                'category': technical,
                'summary': 'Complete guide to our API endpoints and authentication.',
                'content': '''<h2>API Documentation</h2>
                <p>Our API provides programmatic access to all platform features.</p>
                
                <h3>Authentication</h3>
                <p>All API requests require authentication using an API key.</p>
                <code>Authorization: Bearer YOUR_API_KEY</code>
                
                <h3>Rate Limits</h3>
                <p>Standard accounts are limited to 1000 requests per hour.</p>
                
                <h3>Response Format</h3>
                <p>All responses are returned in JSON format.</p>''',
                'is_published': True,
                'is_featured': True,
            },
            {
                'title': 'Common Login Issues and Solutions',
                'slug': 'common-login-issues',
                'category': troubleshooting,
                'summary': 'Troubleshoot common login problems and learn how to resolve them.',
                'content': '''<h2>Login Troubleshooting</h2>
                <p>Having trouble logging in? Here are some common issues and solutions.</p>
                
                <h3>Forgot Password</h3>
                <p>Click "Forgot Password" on the login page to reset your password via email.</p>
                
                <h3>Account Locked</h3>
                <p>After multiple failed login attempts, your account may be temporarily locked for security.</p>
                
                <h3>Browser Issues</h3>
                <p>Clear your browser cache and cookies, or try a different browser.</p>
                
                <h3>Still Having Issues?</h3>
                <p>Contact our support team for personalized assistance.</p>''',
                'is_published': True,
                'is_featured': False,
            },
            {
                'title': 'How to Update Your Payment Method',
                'slug': 'update-payment-method',
                'category': account_billing,
                'summary': 'Step-by-step guide to updating your payment information.',
                'content': '''<h2>Updating Payment Information</h2>
                <p>Keep your payment method up to date to avoid service interruptions.</p>
                
                <h3>Steps to Update</h3>
                <ol>
                    <li>Go to Account Settings</li>
                    <li>Click on "Billing & Payments"</li>
                    <li>Select "Update Payment Method"</li>
                    <li>Enter your new payment details</li>
                    <li>Click "Save Changes"</li>
                </ol>
                
                <h3>Supported Payment Methods</h3>
                <p>We accept all major credit cards, PayPal, and bank transfers.</p>''',
                'is_published': True,
                'is_featured': False,
            },
            {
                'title': 'Security Best Practices',
                'slug': 'security-best-practices',
                'category': KnowledgeBaseCategory.objects.filter(slug='security-privacy').first(),
                'summary': 'Essential security practices to keep your account safe.',
                'content': '''<h2>Account Security</h2>
                <p>Follow these best practices to keep your account secure.</p>
                
                <h3>Use Strong Passwords</h3>
                <p>Create complex passwords with a mix of letters, numbers, and symbols.</p>
                
                <h3>Enable Two-Factor Authentication</h3>
                <p>Add an extra layer of security with 2FA.</p>
                
                <h3>Regular Security Audits</h3>
                <p>Review your account activity regularly for any suspicious behavior.</p>
                
                <h3>Keep Software Updated</h3>
                <p>Always use the latest version of our software for the best security.</p>''',
                'is_published': True,
                'is_featured': True,
            },
        ]

        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}')

