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 = {
                'enterprise-content': {
                    'name': 'Enterprise Content',
                    'description': 'Enterprise-grade solutions for modern businesses',
                    'display_order': 1
                }
            }
            
            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': 'Custom Software Development',
                    'description': 'We design and build tailored digital solutions that align precisely with your business goals — delivering reliable, scalable, and future-ready applications that drive measurable value.',
                    'short_description': 'Tailored digital solutions aligned with your business goals.',
                    'slug': 'custom-software-development',
                    'icon': 'code',
                    'price': '50000.00',
                    'category_slug': 'enterprise-content',
                    'duration': '12-20 weeks',
                    'deliverables': 'Custom Application, System Architecture, Database Design, API Development, User Interface, Testing Suite, Deployment Setup, Documentation, Training, 6 Months Support',
                    'technologies': 'React, Next.js, TypeScript, Node.js, Python, PostgreSQL, MongoDB, Redis, AWS, Docker, Kubernetes',
                    'process_steps': 'Requirements Analysis, Solution Design, Architecture Planning, Development, Testing, Deployment, Training, Launch Support',
                    'featured': True,
                    'display_order': 1,
                    'features': [
                        {'title': 'Custom Solutions', 'description': 'Tailored applications built for your specific needs', 'icon': 'cogs'},
                        {'title': 'Scalable Architecture', 'description': 'Built to grow with your business', 'icon': 'expand'},
                        {'title': 'Future-Ready', 'description': 'Modern tech stack for long-term sustainability', 'icon': 'rocket'},
                        {'title': 'Business Alignment', 'description': 'Solutions that drive measurable business value', 'icon': 'chart-line'},
                        {'title': 'Reliable', 'description': 'Enterprise-grade reliability and performance', 'icon': 'shield'},
                        {'title': 'Full Support', 'description': 'Comprehensive training and ongoing support', 'icon': 'headset'}
                    ]
                },
                {
                    'title': 'Data Replication',
                    'description': 'We ensure secure, real-time synchronization across your databases and systems — maintaining data accuracy, consistency, and availability for mission-critical operations.',
                    'short_description': 'Secure real-time data synchronization across systems.',
                    'slug': 'data-replication',
                    'icon': 'sync',
                    'price': '35000.00',
                    'category_slug': 'enterprise-content',
                    'duration': '8-12 weeks',
                    'deliverables': 'Replication System, Data Pipeline, Monitoring Dashboard, Conflict Resolution, Backup Strategy, Security Configuration, Performance Tuning, Documentation, 6 Months Support',
                    'technologies': 'PostgreSQL, MySQL, MongoDB, Redis, Apache Kafka, AWS DMS, Azure Data Sync, Change Data Capture, ETL Tools',
                    'process_steps': 'Data Assessment, Architecture Design, Pipeline Setup, Testing, Security Implementation, Monitoring Setup, Optimization, Documentation, Go-live',
                    'featured': True,
                    'display_order': 2,
                    'features': [
                        {'title': 'Real-Time Sync', 'description': 'Instant data synchronization across systems', 'icon': 'bolt'},
                        {'title': 'Data Accuracy', 'description': 'Ensures consistency and accuracy across databases', 'icon': 'check-circle'},
                        {'title': 'High Availability', 'description': 'Mission-critical data always available', 'icon': 'server'},
                        {'title': 'Secure Transfer', 'description': 'Encrypted data transmission and storage', 'icon': 'lock'},
                        {'title': 'Conflict Resolution', 'description': 'Automated handling of data conflicts', 'icon': 'cogs'},
                        {'title': 'Performance', 'description': 'Optimized for minimal impact on operations', 'icon': 'gauge'}
                    ]
                },
                {
                    'title': 'Incident Management SaaS',
                    'description': 'We provide intelligent, cloud-based incident management tools that empower teams to detect, respond, and resolve issues faster — minimizing downtime and protecting customer trust.',
                    'short_description': 'Cloud-based incident management for faster issue resolution.',
                    'slug': 'incident-management-saas',
                    'icon': 'bell',
                    'price': '45000.00',
                    'category_slug': 'enterprise-content',
                    'duration': '16-20 weeks',
                    'deliverables': 'SaaS Platform, Incident Dashboard, Alert System, Integration APIs, Mobile App, Reporting Tools, Analytics, Automation Workflows, Documentation, 12 Months Support',
                    'technologies': 'React, Node.js, TypeScript, PostgreSQL, Redis, WebSockets, AWS, Kubernetes, PagerDuty API, Slack Integration, Twilio',
                    'process_steps': 'Requirements Analysis, Platform Design, Core Development, Integration Development, Testing, Security Audit, Deployment, Training, Launch',
                    'featured': True,
                    'display_order': 3,
                    'features': [
                        {'title': 'Intelligent Detection', 'description': 'AI-powered incident detection and alerting', 'icon': 'brain'},
                        {'title': 'Rapid Response', 'description': 'Tools to respond and resolve issues faster', 'icon': 'bolt'},
                        {'title': 'Minimize Downtime', 'description': 'Reduce system downtime and service disruption', 'icon': 'clock'},
                        {'title': 'Team Collaboration', 'description': 'Empower teams with collaborative tools', 'icon': 'users'},
                        {'title': 'Cloud-Based', 'description': 'Accessible anywhere, anytime', 'icon': 'cloud'},
                        {'title': 'Customer Trust', 'description': 'Protect and maintain customer confidence', 'icon': 'shield'}
                    ]
                },
                {
                    'title': 'AI-Powered Business Intelligence',
                    'description': 'We transform enterprise data into actionable insights with advanced analytics and AI — enabling smarter decisions, performance optimization, and data-driven innovation.',
                    'short_description': 'Transform data into insights with AI and advanced analytics.',
                    'slug': 'ai-powered-business-intelligence',
                    'icon': 'brain',
                    'price': '60000.00',
                    'category_slug': 'enterprise-content',
                    'duration': '20-24 weeks',
                    'deliverables': 'BI Platform, Machine Learning Models, Data Pipeline, Interactive Dashboards, Predictive Analytics, Report Generation, API Integration, Model Training, Documentation, 12 Months Support',
                    'technologies': 'Python, TensorFlow, PyTorch, Pandas, Scikit-learn, React, D3.js, Tableau, PostgreSQL, Snowflake, AWS SageMaker, Apache Spark',
                    'process_steps': 'Data Analysis, Model Development, Dashboard Design, Pipeline Development, Training, Integration, Testing, Optimization, Deployment, Training',
                    'featured': True,
                    'display_order': 4,
                    'features': [
                        {'title': 'Actionable Insights', 'description': 'Transform raw data into meaningful insights', 'icon': 'lightbulb'},
                        {'title': 'Advanced Analytics', 'description': 'AI-powered analytics and predictions', 'icon': 'chart-line'},
                        {'title': 'Smart Decisions', 'description': 'Enable data-driven decision making', 'icon': 'brain'},
                        {'title': 'Performance Optimization', 'description': 'Identify and optimize business performance', 'icon': 'gauge'},
                        {'title': 'Data-Driven Innovation', 'description': 'Unlock new opportunities through data', 'icon': 'rocket'},
                        {'title': 'Enterprise Scale', 'description': 'Built to handle enterprise data volumes', 'icon': 'database'}
                    ]
                },
                {
                    'title': 'Backend Engineering',
                    'description': 'We architect and optimize high-performance backend systems — ensuring your applications run securely, efficiently, and scale effortlessly as your business grows.',
                    'short_description': 'High-performance backend systems that scale effortlessly.',
                    'slug': 'backend-engineering',
                    'icon': 'server',
                    'price': '40000.00',
                    'category_slug': 'enterprise-content',
                    'duration': '10-16 weeks',
                    'deliverables': 'Backend Architecture, API Development, Database Design, Authentication System, Caching Strategy, Performance Optimization, Security Implementation, Testing, Documentation, 6 Months Support',
                    'technologies': 'Node.js, Python, Django, FastAPI, PostgreSQL, MongoDB, Redis, RabbitMQ, GraphQL, REST, Docker, Kubernetes, AWS',
                    'process_steps': 'Architecture Design, Database Modeling, API Development, Security Implementation, Optimization, Testing, Deployment, Monitoring Setup, Documentation',
                    'featured': True,
                    'display_order': 5,
                    'features': [
                        {'title': 'High Performance', 'description': 'Optimized for speed and efficiency', 'icon': 'gauge'},
                        {'title': 'Secure', 'description': 'Enterprise-grade security implementation', 'icon': 'shield'},
                        {'title': 'Scalable', 'description': 'Scales effortlessly with business growth', 'icon': 'expand'},
                        {'title': 'Efficient', 'description': 'Resource-optimized for cost efficiency', 'icon': 'cogs'},
                        {'title': 'Reliable', 'description': 'Built for uptime and reliability', 'icon': 'check-circle'},
                        {'title': 'Modern Architecture', 'description': 'Microservices and cloud-native design', 'icon': 'cloud'}
                    ]
                },
                {
                    'title': 'Frontend Engineering',
                    'description': 'We craft responsive, accessible, and engaging user interfaces — blending performance with design to deliver exceptional digital experiences across devices and platforms.',
                    'short_description': 'Responsive, engaging UIs for exceptional digital experiences.',
                    'slug': 'frontend-engineering',
                    'icon': 'palette',
                    'price': '35000.00',
                    'category_slug': 'enterprise-content',
                    'duration': '10-14 weeks',
                    'deliverables': 'Frontend Application, Component Library, Responsive Design, Accessibility Implementation, Performance Optimization, Testing Suite, Documentation, Style Guide, 6 Months Support',
                    'technologies': 'React, Next.js, TypeScript, Vue.js, Tailwind CSS, Material-UI, Redux, GraphQL, Jest, Cypress, Webpack, Vite',
                    'process_steps': 'UI/UX Design, Component Development, Responsive Implementation, Accessibility Audit, Performance Optimization, Testing, Browser Compatibility, Deployment',
                    'featured': True,
                    'display_order': 6,
                    'features': [
                        {'title': 'Responsive Design', 'description': 'Flawless experience across all devices', 'icon': 'mobile'},
                        {'title': 'Accessible', 'description': 'WCAG compliant for all users', 'icon': 'universal-access'},
                        {'title': 'Engaging UX', 'description': 'Beautiful, intuitive user experiences', 'icon': 'heart'},
                        {'title': 'High Performance', 'description': 'Optimized for speed and efficiency', 'icon': 'bolt'},
                        {'title': 'Modern Design', 'description': 'Contemporary design patterns and aesthetics', 'icon': 'palette'},
                        {'title': 'Cross-Platform', 'description': 'Works seamlessly across browsers and platforms', 'icon': 'window-maximize'}
                    ]
                },
                {
                    'title': 'External Systems Integrations',
                    'description': 'We connect everything — from fiscal printers and payment terminals to ERP and cloud platforms — enabling enterprises to operate seamlessly across physical and digital environments.',
                    'short_description': 'Connect systems for seamless enterprise operations.',
                    'slug': 'external-systems-integrations',
                    'icon': 'plug',
                    'price': '45000.00',
                    'category_slug': 'enterprise-content',
                    'duration': '12-18 weeks',
                    'deliverables': 'Integration Platform, API Connectors, Payment Gateway Integration, ERP Integration, Device Integration, Middleware Development, Testing Suite, Security Implementation, Documentation, 6 Months Support',
                    'technologies': 'REST APIs, GraphQL, SOAP, gRPC, Kafka, RabbitMQ, OAuth 2.0, SAP, Salesforce, Stripe, PayPal, IoT Protocols, Node.js, Python',
                    'process_steps': 'Systems Analysis, Integration Design, API Development, Device Setup, Testing, Security Review, Deployment, Monitoring, Documentation, Training',
                    'featured': True,
                    'display_order': 7,
                    'features': [
                        {'title': 'Universal Connectivity', 'description': 'Connect any system, device, or platform', 'icon': 'network-wired'},
                        {'title': 'Payment Integration', 'description': 'Payment terminals and gateway integration', 'icon': 'credit-card'},
                        {'title': 'ERP Integration', 'description': 'Seamless ERP and business system integration', 'icon': 'building'},
                        {'title': 'IoT Devices', 'description': 'Connect physical devices like fiscal printers', 'icon': 'print'},
                        {'title': 'Cloud Platforms', 'description': 'Integration with major cloud platforms', 'icon': 'cloud'},
                        {'title': 'Seamless Operations', 'description': 'Unified operations across all environments', 'icon': 'sync'}
                    ]
                }
            ]

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