#!/usr/bin/env python
"""
Django management command to:
1. Migrate existing Keywords to SeedKeywords
2. Delete all planner and writer module data
3. Clean up relationships

Usage: python manage.py migrate_keywords_to_seed
"""
from django.core.management.base import BaseCommand
from django.db import transaction
from django.db.models import Q
from igny8_core.modules.planner.models import Keywords, Clusters, ContentIdeas
from igny8_core.modules.writer.models import Tasks, Content, Images
from igny8_core.auth.models import SeedKeyword, Industry, IndustrySector, Site, Sector


class Command(BaseCommand):
    help = 'Migrate Keywords to SeedKeywords and clean up planner/writer data'

    def add_arguments(self, parser):
        parser.add_argument(
            '--dry-run',
            action='store_true',
            help='Show what would be done without making changes',
        )

    def handle(self, *args, **options):
        dry_run = options['dry_run']
        
        if dry_run:
            self.stdout.write(self.style.WARNING('DRY RUN MODE - No changes will be made'))
        
        with transaction.atomic():
            # Step 1: Migrate Keywords to SeedKeywords
            self.stdout.write('=' * 60)
            self.stdout.write('Step 1: Migrating Keywords to SeedKeywords')
            self.stdout.write('=' * 60)
            
            # Get all keywords with valid industry and industry_sector relationships
            keywords = Keywords.objects.select_related(
                'site', 'sector', 'sector__industry_sector', 'site__industry'
            ).filter(
                site__industry__isnull=False,
                sector__industry_sector__isnull=False
            ).distinct()
            
            total_keywords = keywords.count()
            self.stdout.write(f'Found {total_keywords} keywords to migrate')
            
            created_count = 0
            skipped_count = 0
            errors = []
            
            # Group by unique (keyword, industry, sector) to avoid duplicates
            seen_combinations = set()
            
            for keyword in keywords:
                try:
                    industry = keyword.site.industry
                    industry_sector = keyword.sector.industry_sector
                    
                    if not industry or not industry_sector:
                        skipped_count += 1
                        continue
                    
                    # Create unique key for deduplication
                    unique_key = (keyword.keyword.lower().strip(), industry.id, industry_sector.id)
                    
                    if unique_key in seen_combinations:
                        skipped_count += 1
                        continue
                    
                    seen_combinations.add(unique_key)
                    
                    # Check if SeedKeyword already exists
                    existing = SeedKeyword.objects.filter(
                        keyword__iexact=keyword.keyword.strip(),
                        industry=industry,
                        sector=industry_sector
                    ).first()
                    
                    if existing:
                        skipped_count += 1
                        self.stdout.write(f'  ⏭️  Skipped (exists): "{keyword.keyword}" for {industry.name} - {industry_sector.name}')
                        continue
                    
                    if not dry_run:
                        # Create SeedKeyword
                        seed_keyword = SeedKeyword.objects.create(
                            keyword=keyword.keyword.strip(),
                            industry=industry,
                            sector=industry_sector,
                            volume=keyword.volume or 0,
                            difficulty=keyword.difficulty or 0,
                            intent=keyword.intent or 'informational',
                            is_active=True
                        )
                        created_count += 1
                        self.stdout.write(
                            self.style.SUCCESS(
                                f'  ✅ Created: "{seed_keyword.keyword}" for {industry.name} - {industry_sector.name}'
                            )
                        )
                    else:
                        created_count += 1
                        self.stdout.write(
                            f'  [DRY RUN] Would create: "{keyword.keyword}" for {industry.name} - {industry_sector.name}'
                        )
                        
                except Exception as e:
                    error_msg = f'Error migrating keyword "{keyword.keyword}" (ID: {keyword.id}): {str(e)}'
                    errors.append(error_msg)
                    self.stdout.write(self.style.ERROR(f'  ❌ {error_msg}'))
            
            self.stdout.write('')
            self.stdout.write(f'  Created: {created_count}')
            self.stdout.write(f'  Skipped: {skipped_count}')
            if errors:
                self.stdout.write(self.style.ERROR(f'  Errors: {len(errors)}'))
            
            if not dry_run:
                # Step 2: Delete all planner and writer module data
                self.stdout.write('')
                self.stdout.write('=' * 60)
                self.stdout.write('Step 2: Deleting planner and writer module data')
                self.stdout.write('=' * 60)
                
                # Delete in order to respect foreign key constraints
                # 1. Delete M2M relationships first
                self.stdout.write('Deleting M2M relationships...')
                tasks_keywords_count = Tasks.objects.filter(keyword_objects__isnull=False).count()
                content_ideas_keywords_count = ContentIdeas.objects.filter(keyword_objects__isnull=False).count()
                
                # Clear M2M relationships
                for task in Tasks.objects.all():
                    task.keyword_objects.clear()
                for idea in ContentIdeas.objects.all():
                    idea.keyword_objects.clear()
                
                self.stdout.write(f'  ✅ Cleared {tasks_keywords_count} task-keyword relationships')
                self.stdout.write(f'  ✅ Cleared {content_ideas_keywords_count} content-idea-keyword relationships')
                
                # 2. Delete writer module data
                self.stdout.write('Deleting writer module data...')
                images_count = Images.objects.count()
                content_count = Content.objects.count()
                tasks_count = Tasks.objects.count()
                
                Images.objects.all().delete()
                Content.objects.all().delete()
                Tasks.objects.all().delete()
                
                self.stdout.write(f'  ✅ Deleted {images_count} images')
                self.stdout.write(f'  ✅ Deleted {content_count} content records')
                self.stdout.write(f'  ✅ Deleted {tasks_count} tasks')
                
                # 3. Delete planner module data
                self.stdout.write('Deleting planner module data...')
                content_ideas_count = ContentIdeas.objects.count()
                clusters_count = Clusters.objects.count()
                keywords_count = Keywords.objects.count()
                
                ContentIdeas.objects.all().delete()
                Clusters.objects.all().delete()
                Keywords.objects.all().delete()
                
                self.stdout.write(f'  ✅ Deleted {content_ideas_count} content ideas')
                self.stdout.write(f'  ✅ Deleted {clusters_count} clusters')
                self.stdout.write(f'  ✅ Deleted {keywords_count} keywords')
                
            else:
                # Dry run - just show counts
                self.stdout.write('')
                self.stdout.write('=' * 60)
                self.stdout.write('Step 2: Would delete planner and writer module data')
                self.stdout.write('=' * 60)
                
                images_count = Images.objects.count()
                content_count = Content.objects.count()
                tasks_count = Tasks.objects.count()
                content_ideas_count = ContentIdeas.objects.count()
                clusters_count = Clusters.objects.count()
                keywords_count = Keywords.objects.count()
                
                self.stdout.write(f'  [DRY RUN] Would delete {images_count} images')
                self.stdout.write(f'  [DRY RUN] Would delete {content_count} content records')
                self.stdout.write(f'  [DRY RUN] Would delete {tasks_count} tasks')
                self.stdout.write(f'  [DRY RUN] Would delete {content_ideas_count} content ideas')
                self.stdout.write(f'  [DRY RUN] Would delete {clusters_count} clusters')
                self.stdout.write(f'  [DRY RUN] Would delete {keywords_count} keywords')
            
            # Summary
            self.stdout.write('')
            self.stdout.write('=' * 60)
            self.stdout.write('Summary:')
            self.stdout.write('=' * 60)
            if not dry_run:
                self.stdout.write(self.style.SUCCESS(f'✅ Migrated {created_count} keywords to SeedKeywords'))
                self.stdout.write(self.style.SUCCESS('✅ Deleted all planner and writer module data'))
            else:
                self.stdout.write(f'[DRY RUN] Would migrate {created_count} keywords to SeedKeywords')
                self.stdout.write('[DRY RUN] Would delete all planner and writer module data')
            
            if errors:
                self.stdout.write('')
                self.stdout.write(self.style.ERROR('Errors encountered:'))
                for error in errors[:10]:  # Show first 10 errors
                    self.stdout.write(self.style.ERROR(f'  - {error}'))
                if len(errors) > 10:
                    self.stdout.write(self.style.ERROR(f'  ... and {len(errors) - 10} more errors'))
            
            if dry_run:
                self.stdout.write('')
                self.stdout.write(self.style.WARNING('This was a DRY RUN. Run without --dry-run to apply changes.'))

