"""
Django management command to add keywords to sectors
Usage: python manage.py add_keywords_to_sectors --site "Test Site" --keywords-per-sector 5
"""
from django.core.management.base import BaseCommand
from django.db import transaction
from igny8_core.auth.models import Site, Sector
from igny8_core.modules.planner.models import Keywords


class Command(BaseCommand):
    help = 'Add keywords to each sector of a specified site'

    def add_arguments(self, parser):
        parser.add_argument(
            '--site',
            type=str,
            default='Test Site',
            help='Name of the site to add keywords to (default: "Test Site")'
        )
        parser.add_argument(
            '--keywords-per-sector',
            type=int,
            default=5,
            help='Number of keywords to add to each sector (default: 5)'
        )

    def handle(self, *args, **options):
        site_name = options['site']
        keywords_per_sector = options['keywords_per_sector']

        try:
            # Find the site
            site = Site.objects.get(name=site_name)
            self.stdout.write(self.style.SUCCESS(f'Found site: {site.name} (ID: {site.id})'))

            # Find all sectors for this site
            sectors = Sector.objects.filter(site=site, is_active=True)
            
            if not sectors.exists():
                self.stdout.write(self.style.WARNING(f'No active sectors found for site "{site_name}"'))
                return

            self.stdout.write(f'Found {sectors.count()} active sector(s) for site "{site_name}"')

            # Technology-related keywords for technology sectors
            tech_keywords = [
                'artificial intelligence',
                'machine learning',
                'cloud computing',
                'data analytics',
                'cybersecurity',
                'blockchain technology',
                'web development',
                'mobile app development',
                'software engineering',
                'digital transformation',
                'IoT solutions',
                'API development',
                'microservices architecture',
                'devops practices',
                'automated testing',
                'agile methodology',
                'scrum framework',
                'version control systems',
                'container orchestration',
                'serverless computing',
            ]

            total_keywords_created = 0

            with transaction.atomic():
                for sector in sectors:
                    self.stdout.write(f'\nProcessing sector: {sector.name} (ID: {sector.id})')
                    
                    # Get existing keywords for this sector to avoid duplicates
                    existing_keywords = set(
                        Keywords.objects.filter(sector=sector)
                        .values_list('keyword', flat=True)
                    )
                    
                    # Select keywords that don't already exist
                    available_keywords = [kw for kw in tech_keywords if kw.lower() not in existing_keywords]
                    
                    if len(available_keywords) < keywords_per_sector:
                        self.stdout.write(
                            self.style.WARNING(
                                f'Only {len(available_keywords)} unique keywords available. '
                                f'Creating {len(available_keywords)} keywords instead of {keywords_per_sector}.'
                            )
                        )
                    
                    keywords_to_create = available_keywords[:keywords_per_sector]
                    
                    if not keywords_to_create:
                        self.stdout.write(
                            self.style.WARNING(f'All keywords already exist for sector "{sector.name}". Skipping.')
                        )
                        continue
                    
                    # Create keywords
                    created_count = 0
                    for keyword_text in keywords_to_create:
                        keyword, created = Keywords.objects.get_or_create(
                            site=site,
                            sector=sector,
                            keyword=keyword_text,
                            defaults={
                                'account': site.account,
                                'volume': 1000 + (created_count * 100),  # Varying volumes
                                'difficulty': 30 + (created_count * 10),  # Varying difficulty (0-100 scale)
                                'intent': 'informational' if created_count % 2 == 0 else 'commercial',
                                'status': 'active',
                            }
                        )
                        if created:
                            created_count += 1
                            total_keywords_created += 1
                            self.stdout.write(f'  ✓ Created: "{keyword_text}"')
                    
                    self.stdout.write(
                        self.style.SUCCESS(
                            f'Created {created_count} keyword(s) for sector "{sector.name}"'
                        )
                    )

            self.stdout.write(
                self.style.SUCCESS(
                    f'\n✅ Successfully created {total_keywords_created} keyword(s) across {sectors.count()} sector(s)'
                )
            )

        except Site.DoesNotExist:
            self.stdout.write(
                self.style.ERROR(f'Site "{site_name}" not found. Available sites:')
            )
            for site in Site.objects.all():
                self.stdout.write(f'  - {site.name} (ID: {site.id})')
        except Exception as e:
            self.stdout.write(self.style.ERROR(f'Error: {str(e)}'))
            raise

