"""
Django management command to create Home & Garden industry with sectors and keywords
Usage: python manage.py create_home_garden_industry
"""
from django.core.management.base import BaseCommand
from django.db import transaction
from django.utils.text import slugify
from igny8_core.auth.models import Industry, IndustrySector, Site, Sector, Account
from igny8_core.modules.planner.models import Keywords


class Command(BaseCommand):
    help = 'Create Home & Garden industry with sectors and add keywords to each sector'

    def handle(self, *args, **options):
        with transaction.atomic():
            # Step 1: Create or get Home & Garden industry
            industry, created = Industry.objects.get_or_create(
                slug='home-garden',
                defaults={
                    'name': 'Home & Garden',
                    'description': 'Home improvement, gardening, landscaping, and interior design',
                    'is_active': True,
                }
            )
            
            if created:
                self.stdout.write(self.style.SUCCESS(f'✅ Created industry: {industry.name}'))
            else:
                self.stdout.write(f'Industry "{industry.name}" already exists, using existing one.')

            # Step 2: Define Home & Garden sectors with their keywords (max 5 per site)
            sectors_data = [
                {
                    'name': 'Gardening',
                    'slug': 'gardening',
                    'description': 'Plants, flowers, vegetables, and garden maintenance',
                    'keywords': [
                        'organic gardening',
                        'vegetable gardening',
                        'flower garden design',
                        'garden tools',
                        'plant care tips',
                        'composting guide',
                        'garden pest control',
                        'herb garden ideas',
                        'garden irrigation systems',
                        'seasonal planting guide',
                    ]
                },
                {
                    'name': 'Home Improvement',
                    'slug': 'home-improvement',
                    'description': 'DIY projects, renovations, and home repairs',
                    'keywords': [
                        'home renovation ideas',
                        'diy home projects',
                        'kitchen remodeling',
                        'bathroom renovation',
                        'flooring installation',
                        'painting tips',
                        'home repair guide',
                        'power tools review',
                        'home maintenance checklist',
                        'interior design trends',
                    ]
                },
                {
                    'name': 'Landscaping',
                    'slug': 'landscaping',
                    'description': 'Outdoor design, lawn care, and hardscaping',
                    'keywords': [
                        'landscape design ideas',
                        'lawn care tips',
                        'outdoor patio design',
                        'deck building guide',
                        'garden pathways',
                        'outdoor lighting ideas',
                        'lawn mowing tips',
                        'tree planting guide',
                        'outdoor kitchen design',
                        'garden edging ideas',
                    ]
                },
                {
                    'name': 'Interior Design',
                    'slug': 'interior-design',
                    'description': 'Home decoration, furniture, and interior styling',
                    'keywords': [
                        'interior design styles',
                        'home decor ideas',
                        'furniture arrangement',
                        'color scheme ideas',
                        'small space design',
                        'home staging tips',
                        'decoration trends',
                        'room makeover ideas',
                        'interior lighting design',
                        'home organization tips',
                    ]
                },
                {
                    'name': 'Home Decor',
                    'slug': 'home-decor',
                    'description': 'Decorative items, accessories, and home styling',
                    'keywords': [
                        'home decor accessories',
                        'wall art ideas',
                        'curtain design tips',
                        'pillow arrangement',
                        'vase decoration ideas',
                        'home fragrance tips',
                        'decorative mirrors',
                        'rug selection guide',
                        'home accent pieces',
                        'seasonal home decor',
                    ]
                },
            ]

            # Step 3: Create IndustrySector templates
            industry_sectors = []
            for sector_data in sectors_data:
                # Create IndustrySector with suggested_keywords (required field in DB)
                industry_sector, created = IndustrySector.objects.get_or_create(
                    industry=industry,
                    slug=sector_data['slug'],
                    defaults={
                        'name': sector_data['name'],
                        'description': sector_data['description'],
                        'suggested_keywords': sector_data['keywords'],  # JSON array of keywords
                        'is_active': True,
                    }
                )
                industry_sectors.append((industry_sector, sector_data['keywords'], created))
                if created:
                    self.stdout.write(f'  ✓ Created sector template: {industry_sector.name}')
                else:
                    self.stdout.write(f'  Sector template "{industry_sector.name}" already exists')

            self.stdout.write(self.style.SUCCESS(f'\n✅ Created {len([s for s, _, c in industry_sectors if c])} new sector templates'))

            # Step 4: Find or create a site for Home & Garden industry
            # Try to find an existing site, or create one
            site = None
            try:
                # Try to find a site with this industry
                site = Site.objects.filter(industry=industry, is_active=True).first()
                if site:
                    self.stdout.write(f'Found existing site: {site.name} (ID: {site.id})')
            except:
                pass

            if not site:
                # Get the first account or create a test account
                account = Account.objects.first()
                if not account:
                    self.stdout.write(self.style.ERROR('No account found. Please create an account first.'))
                    return

                # Create a new site
                site, created = Site.objects.get_or_create(
                    account=account,
                    slug='home-garden-site',
                    defaults={
                        'name': 'Home & Garden Site',
                        'industry': industry,
                        'is_active': True,
                        'status': 'active',
                    }
                )
                if created:
                    self.stdout.write(self.style.SUCCESS(f'✅ Created site: {site.name} (ID: {site.id})'))
                else:
                    self.stdout.write(f'Using existing site: {site.name}')

            # Step 5: Create actual Sector instances from IndustrySector templates
            created_sectors = []
            for industry_sector, keywords_list, _ in industry_sectors:
                # Check if sector already exists for this site
                sector, sector_created = Sector.objects.get_or_create(
                    site=site,
                    slug=industry_sector.slug,
                    defaults={
                        'industry_sector': industry_sector,
                        'name': industry_sector.name,
                        'description': industry_sector.description,
                        'is_active': True,
                        'status': 'active',
                        'account': site.account,
                    }
                )
                created_sectors.append((sector, keywords_list, sector_created))
                if sector_created:
                    self.stdout.write(f'  ✓ Created sector: {sector.name} (ID: {sector.id})')
                else:
                    self.stdout.write(f'  Sector "{sector.name}" already exists for this site')

            # Step 6: Add 10 keywords to each sector
            total_keywords_created = 0
            for sector, keywords_list, sector_created in created_sectors:
                self.stdout.write(f'\nProcessing sector: {sector.name} (ID: {sector.id})')
                
                # Get existing keywords to avoid duplicates
                existing_keywords = set(
                    Keywords.objects.filter(sector=sector)
                    .values_list('keyword', flat=True)
                )
                
                keywords_to_create = []
                for keyword_text in keywords_list:
                    if keyword_text.lower() not in existing_keywords:
                        keywords_to_create.append(keyword_text)
                
                if len(keywords_to_create) < 10:
                    # If we have fewer than 10 unique keywords, add some generic ones
                    generic_keywords = [
                        f'{sector.name.lower()} tips',
                        f'{sector.name.lower()} guide',
                        f'{sector.name.lower()} ideas',
                        f'best {sector.name.lower()}',
                        f'{sector.name.lower()} products',
                        f'{sector.name.lower()} services',
                        f'{sector.name.lower()} solutions',
                        f'{sector.name.lower()} advice',
                        f'{sector.name.lower()} techniques',
                        f'{sector.name.lower()} trends',
                    ]
                    for gen_kw in generic_keywords:
                        if len(keywords_to_create) >= 10:
                            break
                        if gen_kw.lower() not in existing_keywords and gen_kw.lower() not in [k.lower() for k in keywords_to_create]:
                            keywords_to_create.append(gen_kw)

                # Create keywords (limit to 10)
                created_count = 0
                for keyword_text in keywords_to_create[:10]:
                    keyword, kw_created = Keywords.objects.get_or_create(
                        site=site,
                        sector=sector,
                        keyword=keyword_text.lower(),
                        defaults={
                            'account': site.account,
                            'volume': 500 + (created_count * 50),  # Varying volumes
                            'difficulty': 20 + (created_count * 8),  # Varying difficulty (0-100 scale)
                            'intent': 'informational' if created_count % 2 == 0 else 'commercial',
                            'status': 'active',
                        }
                    )
                    if kw_created:
                        created_count += 1
                        total_keywords_created += 1
                        self.stdout.write(f'  ✓ Created keyword: "{keyword_text}"')
                
                if created_count == 0:
                    self.stdout.write(self.style.WARNING(f'  No new keywords created (all already exist)'))
                else:
                    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:\n'
                    f'   - Industry: {industry.name}\n'
                    f'   - Sector templates: {len(industry_sectors)}\n'
                    f'   - Site sectors: {len(created_sectors)}\n'
                    f'   - Total keywords: {total_keywords_created}\n'
                )
            )

