from django.core.management.base import BaseCommand
from django.db import transaction
from services.models import Service, ServiceCategory, ServiceFeature


class Command(BaseCommand):
    help = 'Import completely fresh service data'

    def handle(self, *args, **options):
        with transaction.atomic():
            # Clear existing data
            ServiceFeature.objects.all().delete()
            Service.objects.all().delete()
            ServiceCategory.objects.all().delete()
            
            self.stdout.write(self.style.WARNING('Cleared existing service data'))
            
            # Create fresh categories
            categories = {
                'web-development': {
                    'name': 'Web Development',
                    'description': 'Custom web applications and modern websites',
                    'display_order': 1
                },
                'mobile-development': {
                    'name': 'Mobile Development',
                    'description': 'Native and cross-platform mobile applications',
                    'display_order': 2
                },
                'api-development': {
                    'name': 'API Development',
                    'description': 'RESTful APIs and microservices architecture',
                    'display_order': 3
                },
                'cloud-services': {
                    'name': 'Cloud Services',
                    'description': 'Cloud migration and infrastructure management',
                    'display_order': 4
                },
                'ai-ml': {
                    'name': 'AI & Machine Learning',
                    'description': 'Artificial intelligence and machine learning solutions',
                    'display_order': 5
                }
            }
            
            created_categories = {}
            for slug, data in categories.items():
                category, created = ServiceCategory.objects.get_or_create(
                    slug=slug,
                    defaults={
                        'name': data['name'],
                        'description': data['description'],
                        'display_order': data['display_order'],
                        'is_active': True
                    }
                )
                created_categories[slug] = category
                self.stdout.write(f'Created category: {category.name}')
            
            # Create fresh services with detailed data
            services_data = [
                {
                    'title': 'Enterprise Web Application',
                    'description': 'Build powerful, scalable web applications tailored to your business needs. Our expert developers use modern frameworks and technologies to create solutions that drive growth and efficiency.',
                    'short_description': 'Custom enterprise web applications with modern architecture and scalable infrastructure.',
                    'slug': 'enterprise-web-application',
                    'icon': 'code',
                    'price': '25000.00',
                    'category_slug': 'web-development',
                    'duration': '8-12 weeks',
                    'deliverables': 'Complete Web Application, Admin Dashboard, User Authentication System, Database Design, API Integration, Responsive Design, Security Implementation, Testing Suite, Deployment Setup, Documentation, Training Materials, 3 Months Support',
                    'technologies': 'React, Next.js, TypeScript, Node.js, PostgreSQL, Redis, AWS, Docker, Kubernetes, Jest, Cypress',
                    'process_steps': 'Discovery & Requirements, UI/UX Design, Architecture Planning, Backend Development, Frontend Development, API Development, Database Setup, Security Implementation, Testing & QA, Deployment, Training, Launch Support',
                    'featured': True,
                    'display_order': 1,
                    'features': [
                        {'title': 'Scalable Architecture', 'description': 'Built with microservices and cloud-native architecture', 'icon': 'cloud'},
                        {'title': 'Advanced Security', 'description': 'Enterprise-grade security with authentication and authorization', 'icon': 'shield'},
                        {'title': 'Real-time Features', 'description': 'WebSocket integration for real-time updates and notifications', 'icon': 'bolt'},
                        {'title': 'Mobile Responsive', 'description': 'Fully responsive design that works on all devices', 'icon': 'mobile'},
                        {'title': 'Performance Optimized', 'description': 'Optimized for speed and performance with caching strategies', 'icon': 'gauge'},
                        {'title': 'Analytics Integration', 'description': 'Built-in analytics and reporting capabilities', 'icon': 'chart-bar'}
                    ]
                },
                {
                    'title': 'Cross-Platform Mobile App',
                    'description': 'Create stunning mobile applications for iOS and Android platforms. We deliver native and cross-platform solutions that provide exceptional user experiences and drive engagement.',
                    'short_description': 'Native and cross-platform mobile applications with modern UI/UX design.',
                    'slug': 'cross-platform-mobile-app',
                    'icon': 'mobile',
                    'price': '35000.00',
                    'category_slug': 'mobile-development',
                    'duration': '12-16 weeks',
                    'deliverables': 'iOS Mobile App, Android Mobile App, Admin Panel, Backend API, Push Notifications, Offline Support, App Store Submission, Google Play Submission, User Documentation, Admin Guide, Testing Suite, 6 Months Support',
                    'technologies': 'React Native, TypeScript, Node.js, MongoDB, Firebase, AWS, App Store Connect, Google Play Console, Jest, Detox',
                    'process_steps': 'Market Research, UI/UX Design, Prototyping, Backend Development, Mobile App Development, API Integration, Testing, App Store Optimization, Submission Process, Launch Strategy, Post-launch Support',
                    'featured': True,
                    'display_order': 2,
                    'features': [
                        {'title': 'Cross-Platform', 'description': 'Single codebase for both iOS and Android platforms', 'icon': 'mobile'},
                        {'title': 'Native Performance', 'description': 'Optimized performance using native components and modules', 'icon': 'gauge'},
                        {'title': 'Offline Support', 'description': 'Full offline functionality with data synchronization', 'icon': 'wifi'},
                        {'title': 'Push Notifications', 'description': 'Real-time push notifications for user engagement', 'icon': 'bell'},
                        {'title': 'App Store Ready', 'description': 'Complete app store submission and approval process', 'icon': 'store'},
                        {'title': 'Analytics Dashboard', 'description': 'Comprehensive analytics and user behavior tracking', 'icon': 'chart-line'}
                    ]
                },
                {
                    'title': 'RESTful API Development',
                    'description': 'Build robust, scalable APIs that power your applications and enable seamless integration with third-party services. Our APIs are designed for performance, security, and maintainability.',
                    'short_description': 'Enterprise-grade RESTful APIs with comprehensive documentation and security.',
                    'slug': 'restful-api-development',
                    'icon': 'api',
                    'price': '15000.00',
                    'category_slug': 'api-development',
                    'duration': '4-6 weeks',
                    'deliverables': 'RESTful API, API Documentation, Authentication System, Rate Limiting, API Testing Suite, Postman Collection, SDK Development, Integration Examples, Performance Monitoring, Security Audit, Deployment Guide, 3 Months Support',
                    'technologies': 'Node.js, Express, TypeScript, PostgreSQL, Redis, JWT, Swagger, Postman, Jest, AWS API Gateway, Docker',
                    'process_steps': 'API Planning, Database Design, Authentication Setup, Endpoint Development, Documentation, Testing, Security Review, Performance Optimization, Deployment, Integration Testing, Monitoring Setup',
                    'featured': False,
                    'display_order': 3,
                    'features': [
                        {'title': 'RESTful Design', 'description': 'Clean, intuitive API design following REST principles', 'icon': 'code'},
                        {'title': 'Comprehensive Documentation', 'description': 'Interactive API documentation with examples', 'icon': 'book'},
                        {'title': 'Authentication & Security', 'description': 'JWT-based authentication with rate limiting', 'icon': 'shield'},
                        {'title': 'Performance Optimized', 'description': 'Caching and optimization for high performance', 'icon': 'gauge'},
                        {'title': 'SDK Support', 'description': 'Client SDKs for easy integration', 'icon': 'puzzle-piece'},
                        {'title': 'Monitoring & Analytics', 'description': 'Built-in monitoring and usage analytics', 'icon': 'chart-bar'}
                    ]
                },
                {
                    'title': 'Cloud Migration & DevOps',
                    'description': 'Migrate your existing infrastructure to the cloud with minimal downtime. We help you leverage cloud technologies for improved scalability, security, and cost efficiency.',
                    'short_description': 'Complete cloud migration with DevOps automation and monitoring.',
                    'slug': 'cloud-migration-devops',
                    'icon': 'cloud',
                    'price': '45000.00',
                    'category_slug': 'cloud-services',
                    'duration': '16-20 weeks',
                    'deliverables': 'Cloud Infrastructure Setup, Application Migration, CI/CD Pipeline, Monitoring Setup, Security Configuration, Backup Strategy, Disaster Recovery Plan, Cost Optimization, Performance Tuning, Documentation, Training, 6 Months Support',
                    'technologies': 'AWS, Azure, Google Cloud, Docker, Kubernetes, Terraform, Jenkins, GitLab CI, Prometheus, Grafana, ELK Stack',
                    'process_steps': 'Infrastructure Assessment, Migration Planning, Security Audit, Infrastructure Setup, Application Migration, CI/CD Implementation, Monitoring Setup, Testing, Go-live, Optimization, Documentation, Training',
                    'featured': True,
                    'display_order': 4,
                    'features': [
                        {'title': 'Zero Downtime Migration', 'description': 'Seamless migration with minimal service interruption', 'icon': 'clock'},
                        {'title': 'Cost Optimization', 'description': 'Optimized cloud resources for maximum cost efficiency', 'icon': 'dollar-sign'},
                        {'title': 'Security First', 'description': 'Enhanced security with cloud-native security features', 'icon': 'shield'},
                        {'title': 'Automated DevOps', 'description': 'Complete CI/CD pipeline with automated deployments', 'icon': 'cogs'},
                        {'title': 'Monitoring & Alerting', 'description': 'Comprehensive monitoring and alerting system', 'icon': 'bell'},
                        {'title': 'Scalability', 'description': 'Auto-scaling infrastructure for handling traffic spikes', 'icon': 'expand'}
                    ]
                },
                {
                    'title': 'AI-Powered Business Intelligence',
                    'description': 'Transform your business data into actionable insights with AI-powered analytics and machine learning solutions. Make data-driven decisions with advanced predictive analytics.',
                    'short_description': 'AI-powered business intelligence and predictive analytics platform.',
                    'slug': 'ai-powered-business-intelligence',
                    'icon': 'brain',
                    'price': '55000.00',
                    'category_slug': 'ai-ml',
                    'duration': '20-24 weeks',
                    'deliverables': 'AI Analytics Platform, Machine Learning Models, Data Pipeline, Dashboard Development, Predictive Analytics, Report Generation, API Integration, Data Visualization, Model Training, Performance Monitoring, Documentation, 12 Months Support',
                    'technologies': 'Python, TensorFlow, PyTorch, Pandas, NumPy, Scikit-learn, React, D3.js, PostgreSQL, Redis, AWS SageMaker, Docker',
                    'process_steps': 'Data Analysis, Model Selection, Data Pipeline Development, Model Training, Dashboard Development, API Development, Testing, Deployment, Performance Monitoring, Optimization, Documentation, Training',
                    'featured': True,
                    'display_order': 5,
                    'features': [
                        {'title': 'Predictive Analytics', 'description': 'Advanced ML models for business forecasting', 'icon': 'chart-line'},
                        {'title': 'Real-time Insights', 'description': 'Live data processing and real-time analytics', 'icon': 'bolt'},
                        {'title': 'Interactive Dashboards', 'description': 'Beautiful, interactive data visualization', 'icon': 'chart-bar'},
                        {'title': 'Automated Reports', 'description': 'Automated report generation and distribution', 'icon': 'file-alt'},
                        {'title': 'Data Integration', 'description': 'Seamless integration with existing data sources', 'icon': 'plug'},
                        {'title': 'Scalable Architecture', 'description': 'Cloud-native architecture for handling big data', 'icon': 'cloud'}
                    ]
                },
                {
                    'title': 'E-commerce Platform',
                    'description': 'Build a complete e-commerce solution with modern features, secure payment processing, and advanced analytics. Create an online store that converts visitors into customers.',
                    'short_description': 'Complete e-commerce platform with payment processing and analytics.',
                    'slug': 'ecommerce-platform',
                    'icon': 'shopping-cart',
                    'price': '30000.00',
                    'category_slug': 'web-development',
                    'duration': '10-14 weeks',
                    'deliverables': 'E-commerce Website, Admin Dashboard, Payment Integration, Inventory Management, Order Management, Customer Portal, Analytics Dashboard, SEO Optimization, Mobile App, Testing Suite, Documentation, 6 Months Support',
                    'technologies': 'React, Next.js, Node.js, PostgreSQL, Stripe, PayPal, AWS, Redis, Elasticsearch, Jest, Cypress',
                    'process_steps': 'Requirements Analysis, UI/UX Design, Database Design, Backend Development, Frontend Development, Payment Integration, Testing, SEO Optimization, Performance Tuning, Launch, Marketing Setup, Support',
                    'featured': False,
                    'display_order': 6,
                    'features': [
                        {'title': 'Secure Payments', 'description': 'Multiple payment gateways with PCI compliance', 'icon': 'credit-card'},
                        {'title': 'Inventory Management', 'description': 'Advanced inventory tracking and management', 'icon': 'box'},
                        {'title': 'Customer Analytics', 'description': 'Detailed customer behavior and sales analytics', 'icon': 'chart-bar'},
                        {'title': 'Mobile Optimized', 'description': 'Fully responsive design for mobile shopping', 'icon': 'mobile'},
                        {'title': 'SEO Ready', 'description': 'Built-in SEO optimization for better visibility', 'icon': 'search'},
                        {'title': 'Multi-vendor Support', 'description': 'Support for multiple vendors and marketplace', 'icon': 'store'}
                    ]
                }
            ]

            for service_data in services_data:
                # Extract features before creating service
                features = service_data.pop('features', [])
                category_slug = service_data.pop('category_slug')
                
                # Create service
                service = Service.objects.create(
                    category=created_categories[category_slug],
                    **service_data
                )
                
                self.stdout.write(f'Created service: {service.title}')
                
                # Create features for the service
                for feature_data in features:
                    ServiceFeature.objects.create(
                        service=service,
                        **feature_data
                    )
                
                self.stdout.write(f'  Added {len(features)} features')

        self.stdout.write(
            self.style.SUCCESS('Successfully imported fresh service data!')
        )
        self.stdout.write(
            self.style.SUCCESS(f'Created {Service.objects.count()} services with {ServiceFeature.objects.count()} features')
        )
