"""
Management command to import enterprise-grade sample data for About Us
with images downloaded from Unsplash.
"""
import urllib.request
import urllib.parse
import json
from io import BytesIO
from django.core.management.base import BaseCommand
from django.core.files.base import ContentFile
from django.db import transaction
from about.models import (
    AboutBanner, AboutStat, AboutSocialLink,
    AboutService, AboutFeature,
    AboutProcess, AboutProcessStep,
    AboutJourney, AboutMilestone
)


class Command(BaseCommand):
    help = 'Import enterprise-grade sample data for About Us with images from Unsplash'

    def add_arguments(self, parser):
        parser.add_argument(
            '--unsplash-key',
            type=str,
            help='Unsplash API access key (optional, uses Unsplash Source API if not provided)',
        )
        parser.add_argument(
            '--width',
            type=int,
            default=1200,
            help='Image width in pixels (default: 1200)',
        )
        parser.add_argument(
            '--height',
            type=int,
            default=800,
            help='Image height in pixels (default: 800)',
        )
        parser.add_argument(
            '--update-existing',
            action='store_true',
            help='Update existing about data instead of skipping it',
        )

    def download_image_from_unsplash(self, keyword, width=1200, height=800, api_key=None):
        """
        Download an image from Unsplash based on keyword.
        
        Args:
            keyword: Search keyword for the image
            width: Image width in pixels
            height: Image height in pixels
            api_key: Optional Unsplash API access key
        
        Returns:
            BytesIO object containing the image data, or None if download fails
        """
        try:
            if api_key:
                # Use Unsplash API (requires API key)
                url = "https://api.unsplash.com/photos/random"
                params = {
                    'query': keyword,
                    'orientation': 'landscape',
                    'w': width,
                    'h': height,
                    'client_id': api_key
                }
                query_string = urllib.parse.urlencode(params)
                full_url = f"{url}?{query_string}"
                
                req = urllib.request.Request(full_url)
                with urllib.request.urlopen(req, timeout=30) as response:
                    data = json.loads(response.read().decode())
                    image_url = data['urls']['regular']
            else:
                # Use Unsplash's direct image service (no key required)
                # Using curated enterprise/business images
                image_url = f"https://images.unsplash.com/photo-1552664730-d307ca884978?w={width}&h={height}&fit=crop"
            
            # Download the actual image
            req = urllib.request.Request(image_url)
            req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36')
            with urllib.request.urlopen(req, timeout=30) as img_response:
                image_data = BytesIO(img_response.read())
                image_data.seek(0)
            
            return image_data
        except Exception as e:
            self.stdout.write(
                self.style.WARNING(f'Failed to download image for "{keyword}": {str(e)}')
            )
            return None

    def handle(self, *args, **options):
        unsplash_key = options.get('unsplash_key')
        width = options.get('width', 1200)
        height = options.get('height', 800)
        update_existing = options.get('update_existing', False)

        self.stdout.write(self.style.SUCCESS('Starting enterprise About Us data import...'))

        with transaction.atomic():
            # Clear existing data if updating
            if update_existing:
                self.stdout.write('Clearing existing about data...')
                AboutBanner.objects.all().delete()
                AboutService.objects.all().delete()
                AboutProcess.objects.all().delete()
                AboutJourney.objects.all().delete()

            # Create About Banner
            banner_data = {
                'title': 'Enterprise Software Solutions for Mission-Critical Industries',
                'subtitle': 'GNX Soft Ltd - Your Trusted Enterprise Technology Partner',
                'description': 'GNX Soft Ltd is a leading Bulgarian enterprise software company delivering cutting-edge technology solutions to mission-critical industries worldwide. We empower organizations in Defense & Aerospace, Healthcare & Medical, Telecommunication, Banking, Public Sector, E-commerce, Food & Beverages, and Oil & Energy sectors with innovative, secure, and scalable software platforms that drive digital transformation and operational excellence. Our commitment to EU-based infrastructure, privacy-by-design principles, and defense-grade security makes us the preferred technology partner for organizations that demand the highest levels of reliability, compliance, and data protection.',
                'badge_text': 'Enterprise Software Solutions',
                'badge_icon': 'fa-solid fa-building',
                'cta_text': 'Explore Enterprise Solutions',
                'cta_link': 'services',
                'cta_icon': 'fa-solid fa-arrow-trend-up',
                'is_active': True
            }

            banner, created = AboutBanner.objects.get_or_create(
                title=banner_data['title'],
                defaults=banner_data
            )

            if not created and update_existing:
                for key, value in banner_data.items():
                    setattr(banner, key, value)
                banner.save()

            if created or update_existing:
                self.stdout.write(f'{"Created" if created else "Updated"} banner: {banner.title}')

                # Download banner image
                self.stdout.write('Downloading banner image...')
                image_data = self.download_image_from_unsplash(
                    'enterprise business technology office',
                    width=width,
                    height=height,
                    api_key=unsplash_key
                )
                if image_data:
                    try:
                        filename = 'about-banner.jpg'
                        banner.image.save(
                            filename,
                            ContentFile(image_data.read()),
                            save=True
                        )
                        self.stdout.write(self.style.SUCCESS('  ✓ Banner image saved'))
                    except Exception as e:
                        self.stdout.write(self.style.ERROR(f'  ✗ Failed to save banner image: {str(e)}'))

                # Clear and recreate stats
                if update_existing:
                    AboutStat.objects.filter(banner=banner).delete()
                
                # Create Banner Stats
                stats_data = [
                    {'number': '8', 'label': 'Industry Verticals', 'order': 1},
                    {'number': '99.9%', 'label': 'Uptime SLA', 'order': 2},
                    {'number': '24/7', 'label': 'Enterprise Support', 'order': 3},
                    {'number': '500+', 'label': 'Enterprise Clients', 'order': 4},
                    {'number': '2020', 'label': 'Founded', 'order': 5},
                ]

                for stat_data in stats_data:
                    AboutStat.objects.get_or_create(
                        banner=banner,
                        label=stat_data['label'],
                        defaults=stat_data
                    )

                # Clear and recreate social links
                if update_existing:
                    AboutSocialLink.objects.filter(banner=banner).delete()

                # Create Social Links
                social_links_data = [
                    {
                        'platform': 'LinkedIn',
                        'url': 'https://www.linkedin.com/company/gnxsoft',
                        'icon': 'fa-brands fa-linkedin-in',
                        'aria_label': 'Connect with GNX Soft on LinkedIn',
                        'order': 1
                    },
                    {
                        'platform': 'GitHub',
                        'url': 'https://github.com/gnxsoft',
                        'icon': 'fa-brands fa-github',
                        'aria_label': 'Follow GNX Soft on GitHub',
                        'order': 2
                    },
                    {
                        'platform': 'Twitter',
                        'url': 'https://twitter.com/gnxsoft',
                        'icon': 'fa-brands fa-twitter',
                        'aria_label': 'Follow GNX Soft on Twitter',
                        'order': 3
                    },
                    {
                        'platform': 'Email',
                        'url': 'mailto:info@gnxsoft.com',
                        'icon': 'fa-solid fa-envelope',
                        'aria_label': 'Contact GNX Soft via email',
                        'order': 4
                    },
                ]

                for social_data in social_links_data:
                    AboutSocialLink.objects.get_or_create(
                        banner=banner,
                        platform=social_data['platform'],
                        defaults=social_data
                    )

            # Create About Service
            service_data = {
                'title': 'Enterprise Technology Excellence Across Critical Industries',
                'subtitle': 'About GNX Soft Ltd',
                'description': 'Founded in 2020 and headquartered in Burgas, Bulgaria, GNX Soft Ltd is a premier enterprise software development company specializing in mission-critical solutions for highly regulated industries. Our expert team of 50+ engineers, architects, and consultants delivers secure, scalable, and compliant software solutions to Defense & Aerospace, Healthcare & Medical, Telecommunication, Banking & Finance, Public Sector, E-commerce, Food & Beverages, and Oil & Energy sectors. With EU-based infrastructure spanning Bulgaria, Germany, and Netherlands, we provide enterprise-grade solutions that meet the highest security and regulatory standards including GDPR, HIPAA, PCI-DSS, and industry-specific compliance requirements. Our commitment to privacy-by-design, defense-grade security, and continuous innovation positions us as a trusted technology partner for Fortune 500 companies and government organizations worldwide.',
                'badge_text': 'About GNX Soft Ltd',
                'badge_icon': 'fa-solid fa-users',
                'cta_text': 'Explore Our Solutions',
                'cta_link': 'services',
                'is_active': True
            }

            service, created = AboutService.objects.get_or_create(
                title=service_data['title'],
                defaults=service_data
            )

            if not created and update_existing:
                for key, value in service_data.items():
                    setattr(service, key, value)
                service.save()

            if created or update_existing:
                self.stdout.write(f'{"Created" if created else "Updated"} service: {service.title}')

                # Download service image
                self.stdout.write('Downloading service image...')
                image_data = self.download_image_from_unsplash(
                    'enterprise team collaboration technology',
                    width=width,
                    height=height,
                    api_key=unsplash_key
                )
                if image_data:
                    try:
                        filename = 'about-service.jpg'
                        service.image.save(
                            filename,
                            ContentFile(image_data.read()),
                            save=True
                        )
                        self.stdout.write(self.style.SUCCESS('  ✓ Service image saved'))
                    except Exception as e:
                        self.stdout.write(self.style.ERROR(f'  ✗ Failed to save service image: {str(e)}'))

                # Clear and recreate features
                if update_existing:
                    AboutFeature.objects.filter(service=service).delete()

                # Create Service Features
                features_data = [
                    {
                        'title': 'EU-Based Company',
                        'description': 'Headquartered in Burgas, Bulgaria with EU-wide presence',
                        'icon': 'fa-solid fa-building',
                        'order': 1
                    },
                    {
                        'title': 'EU Infrastructure',
                        'description': 'Data centers in Bulgaria, Germany, and Netherlands',
                        'icon': 'fa-solid fa-server',
                        'order': 2
                    },
                    {
                        'title': '8 Industry Verticals',
                        'description': 'Specialized expertise across critical sectors',
                        'icon': 'fa-solid fa-industry',
                        'order': 3
                    },
                    {
                        'title': '24/7 Enterprise Support',
                        'description': 'Round-the-clock support with SLA guarantees',
                        'icon': 'fa-solid fa-headset',
                        'order': 4
                    },
                    {
                        'title': '500+ Enterprise Clients',
                        'description': 'Trusted by Fortune 500 and government organizations',
                        'icon': 'fa-solid fa-users',
                        'order': 5
                    },
                    {
                        'title': 'Defense-Grade Security',
                        'description': 'Bank-level security with compliance certifications',
                        'icon': 'fa-solid fa-shield-halved',
                        'order': 6
                    },
                ]

                for feature_data in features_data:
                    AboutFeature.objects.get_or_create(
                        service=service,
                        title=feature_data['title'],
                        defaults=feature_data
                    )

            # Create About Process
            process_data = {
                'title': 'Enterprise-Grade Development Methodology',
                'subtitle': 'Our Methodology',
                'description': 'GNX Soft Ltd employs a proven enterprise development methodology that combines agile practices with defense-grade security, regulatory compliance, and enterprise scalability. We follow industry best practices including DevOps, CI/CD, microservices architecture, and privacy-by-design principles to deliver robust, secure, and compliant solutions for highly regulated industries. Every project undergoes rigorous security assessments, Data Protection Impact Assessments (DPIAs), penetration testing, and compliance verification to meet the strictest industry standards including GDPR, HIPAA, PCI-DSS, SOC 2, and ISO 27001. Our methodology emphasizes continuous integration, automated testing, infrastructure as code, and comprehensive documentation to ensure long-term maintainability and scalability.',
                'badge_text': 'Our Methodology',
                'badge_icon': 'fa-solid fa-cogs',
                'cta_text': 'View Our Services',
                'cta_link': 'services',
                'is_active': True
            }

            process, created = AboutProcess.objects.get_or_create(
                title=process_data['title'],
                defaults=process_data
            )

            if not created and update_existing:
                for key, value in process_data.items():
                    setattr(process, key, value)
                process.save()

            if created or update_existing:
                self.stdout.write(f'{"Created" if created else "Updated"} process: {process.title}')

                # Download process image
                self.stdout.write('Downloading process image...')
                image_data = self.download_image_from_unsplash(
                    'enterprise development methodology process',
                    width=width,
                    height=height,
                    api_key=unsplash_key
                )
                if image_data:
                    try:
                        filename = 'about-process.jpg'
                        process.image.save(
                            filename,
                            ContentFile(image_data.read()),
                            save=True
                        )
                        self.stdout.write(self.style.SUCCESS('  ✓ Process image saved'))
                    except Exception as e:
                        self.stdout.write(self.style.ERROR(f'  ✗ Failed to save process image: {str(e)}'))

                # Clear and recreate process steps
                if update_existing:
                    AboutProcessStep.objects.filter(process=process).delete()

                # Create Process Steps
                steps_data = [
                    {
                        'step_number': '01',
                        'title': 'Discovery & Compliance Assessment',
                        'description': 'Requirements analysis, regulatory assessment, DPIA, and security planning',
                        'order': 1
                    },
                    {
                        'step_number': '02',
                        'title': 'Secure Development & Architecture',
                        'description': 'Privacy-by-design, secure coding practices, microservices architecture, and continuous testing',
                        'order': 2
                    },
                    {
                        'step_number': '03',
                        'title': 'Deployment & Integration',
                        'description': 'EU infrastructure deployment, system integration, and performance optimization',
                        'order': 3
                    },
                    {
                        'step_number': '04',
                        'title': 'Security Audit & Compliance',
                        'description': 'Penetration testing, security audits, compliance verification, and certification',
                        'order': 4
                    },
                    {
                        'step_number': '05',
                        'title': 'Support & Continuous Monitoring',
                        'description': '24/7 enterprise support, monitoring, breach response, and continuous improvement',
                        'order': 5
                    },
                ]

                for step_data in steps_data:
                    AboutProcessStep.objects.get_or_create(
                        process=process,
                        step_number=step_data['step_number'],
                        defaults=step_data
                    )

            # Create About Journey
            journey_data = {
                'title': 'Building Enterprise Excellence Since 2020',
                'subtitle': 'Our Journey',
                'description': 'Founded in 2020 in Burgas, Bulgaria, GNX Soft Ltd was established with a clear mission: to deliver world-class enterprise software solutions for mission-critical industries while maintaining the highest standards of security, compliance, and data protection. From our inception, we focused exclusively on enterprise clients in highly regulated sectors including Defense & Aerospace, Healthcare & Medical, Banking, Public Sector, Telecommunication, E-commerce, Food & Beverages, and Oil & Energy. Our commitment to EU-based infrastructure, privacy-by-design principles, and defense-grade security has positioned us as a trusted technology partner for organizations that demand the highest levels of security and regulatory adherence. Today, we serve 500+ enterprise clients across 8 industry verticals, with a team of 50+ experts and EU-wide infrastructure supporting mission-critical operations 24/7.',
                'badge_text': 'Our Journey',
                'badge_icon': 'fa-solid fa-rocket',
                'cta_text': 'Explore Solutions',
                'cta_link': 'services',
                'is_active': True
            }

            journey, created = AboutJourney.objects.get_or_create(
                title=journey_data['title'],
                defaults=journey_data
            )

            if not created and update_existing:
                for key, value in journey_data.items():
                    setattr(journey, key, value)
                journey.save()

            if created or update_existing:
                self.stdout.write(f'{"Created" if created else "Updated"} journey: {journey.title}')

                # Download journey image
                self.stdout.write('Downloading journey image...')
                image_data = self.download_image_from_unsplash(
                    'enterprise growth journey success',
                    width=width,
                    height=height,
                    api_key=unsplash_key
                )
                if image_data:
                    try:
                        filename = 'about-journey.jpg'
                        journey.image.save(
                            filename,
                            ContentFile(image_data.read()),
                            save=True
                        )
                        self.stdout.write(self.style.SUCCESS('  ✓ Journey image saved'))
                    except Exception as e:
                        self.stdout.write(self.style.ERROR(f'  ✗ Failed to save journey image: {str(e)}'))

                # Clear and recreate milestones
                if update_existing:
                    AboutMilestone.objects.filter(journey=journey).delete()

                # Create Journey Milestones
                milestones_data = [
                    {
                        'year': '2020',
                        'title': 'Company Founded',
                        'description': 'GNX Soft Ltd established in Burgas, Bulgaria with focus on enterprise solutions',
                        'order': 1
                    },
                    {
                        'year': '2021',
                        'title': 'Industry Specialization',
                        'description': 'Specialized in 8 mission-critical industries with first enterprise clients',
                        'order': 2
                    },
                    {
                        'year': '2022',
                        'title': 'EU Infrastructure Expansion',
                        'description': 'Deployed EU-wide data centers across Bulgaria, Germany, and Netherlands',
                        'order': 3
                    },
                    {
                        'year': '2023',
                        'title': 'Enterprise Growth',
                        'description': 'Reached 300+ enterprise clients with 50+ expert team members',
                        'order': 4
                    },
                    {
                        'year': '2024',
                        'title': 'Industry Leadership',
                        'description': 'Recognized as leading Bulgarian enterprise software provider with 500+ clients',
                        'order': 5
                    },
                    {
                        'year': '2025',
                        'title': 'Global Expansion',
                        'description': 'Expanding services globally while maintaining EU-based infrastructure and compliance',
                        'order': 6
                    },
                ]

                for milestone_data in milestones_data:
                    AboutMilestone.objects.get_or_create(
                        journey=journey,
                        year=milestone_data['year'],
                        defaults=milestone_data
                    )

        self.stdout.write(
            self.style.SUCCESS('\n✓ Successfully imported enterprise About Us data!')
        )
        if not unsplash_key:
            self.stdout.write(
                self.style.WARNING(
                    '\nNote: Using Unsplash Source API (no key required). '
                    'For better reliability, consider using --unsplash-key with an API key from https://unsplash.com/developers'
                )
            )

