# Generated migration for Phase 2 data migration

from django.db import migrations


def migrate_content_entity_types(apps, schema_editor):
    """Migrate legacy entity_type values to new unified structure"""
    Content = apps.get_model('writer', 'Content')
    
    # Map legacy entity types to new structure
    legacy_mapping = {
        'blog_post': ('post', 'article'),
        'article': ('post', 'article'),
        'taxonomy': ('taxonomy_term', None),
    }
    
    for content in Content.objects.all():
        old_type = content.entity_type
        
        if old_type in legacy_mapping:
            new_type, format_type = legacy_mapping[old_type]
            content.entity_type = new_type
            if format_type and new_type == 'post':
                content.content_format = format_type
            content.save(update_fields=['entity_type', 'content_format'])


def migrate_task_entity_types(apps, schema_editor):
    """Migrate task entity_type to content when task has associated content"""
    Content = apps.get_model('writer', 'Content')
    Tasks = apps.get_model('writer', 'Tasks')
    
    for task in Tasks.objects.filter(entity_type__isnull=False):
        try:
            content = Content.objects.get(task=task)
            
            # Map task entity_type to content
            if task.entity_type == 'blog_post':
                content.entity_type = 'post'
                content.content_format = 'article'
            elif task.entity_type == 'article':
                content.entity_type = 'post'
                content.content_format = 'article'
            elif task.entity_type == 'product':
                content.entity_type = 'product'
            elif task.entity_type == 'service':
                content.entity_type = 'service'
            elif task.entity_type == 'taxonomy':
                content.entity_type = 'taxonomy_term'
            elif task.entity_type == 'page':
                content.entity_type = 'page'
            
            # Migrate cluster_role from task
            if task.cluster_role:
                content.cluster_role = task.cluster_role
            
            # Migrate cluster relationship
            if task.cluster_id:
                content.cluster_id = task.cluster_id
            
            content.save()
        except Content.DoesNotExist:
            pass


def migrate_content_categories_tags_to_taxonomy(apps, schema_editor):
    """Migrate JSON categories and tags to ContentTaxonomy M2M"""
    Content = apps.get_model('writer', 'Content')
    ContentTaxonomy = apps.get_model('writer', 'ContentTaxonomy')
    ContentTaxonomyRelation = apps.get_model('writer', 'ContentTaxonomyRelation')
    
    for content in Content.objects.all():
        # Skip if no categories or tags
        if not content.categories and not content.tags:
            continue
        
        # Migrate categories (stored as JSON list)
        if content.categories:
            for category_name in content.categories:
                if isinstance(category_name, str) and category_name.strip():
                    # Get or create taxonomy term
                    taxonomy, created = ContentTaxonomy.objects.get_or_create(
                        site=content.site,
                        slug=category_name.lower().replace(' ', '-')[:255],
                        taxonomy_type='category',
                        defaults={
                            'name': category_name[:255],
                            'account': content.account,
                            'sector': content.sector,
                            'sync_status': 'native',
                        }
                    )
                    # Create relation manually
                    ContentTaxonomyRelation.objects.get_or_create(
                        content=content,
                        taxonomy=taxonomy
                    )
        
        # Migrate tags (stored as JSON list)
        if content.tags:
            for tag_name in content.tags:
                if isinstance(tag_name, str) and tag_name.strip():
                    taxonomy, created = ContentTaxonomy.objects.get_or_create(
                        site=content.site,
                        slug=tag_name.lower().replace(' ', '-')[:255],
                        taxonomy_type='tag',
                        defaults={
                            'name': tag_name[:255],
                            'account': content.account,
                            'sector': content.sector,
                            'sync_status': 'native',
                        }
                    )
                    # Create relation manually
                    ContentTaxonomyRelation.objects.get_or_create(
                        content=content,
                        taxonomy=taxonomy
                    )


def migrate_blueprint_taxonomies(apps, schema_editor):
    """Migrate SiteBlueprintTaxonomy to ContentTaxonomy"""
    try:
        SiteBlueprintTaxonomy = apps.get_model('site_building', 'SiteBlueprintTaxonomy')
        ContentTaxonomy = apps.get_model('writer', 'ContentTaxonomy')
        
        taxonomy_type_mapping = {
            'blog_category': 'category',
            'blog_tag': 'tag',
            'product_category': 'product_cat',
            'product_tag': 'product_tag',
            'product_attribute': 'product_attr',
            'service_category': 'service_cat',
        }
        
        for bp_tax in SiteBlueprintTaxonomy.objects.all():
            new_type = taxonomy_type_mapping.get(bp_tax.taxonomy_type, 'category')
            
            # Create or update ContentTaxonomy
            taxonomy, created = ContentTaxonomy.objects.update_or_create(
                site=bp_tax.site,
                slug=bp_tax.slug,
                taxonomy_type=new_type,
                defaults={
                    'name': bp_tax.name,
                    'description': bp_tax.description or '',
                    'account': bp_tax.account,
                    'sector': bp_tax.sector,
                    'external_id': int(bp_tax.external_reference) if bp_tax.external_reference and bp_tax.external_reference.isdigit() else None,
                    'sync_status': 'imported' if bp_tax.external_reference else 'native',
                    'metadata': bp_tax.metadata if hasattr(bp_tax, 'metadata') else {},
                }
            )
            
            # Migrate cluster relationships
            if hasattr(bp_tax, 'clusters'):
                for cluster in bp_tax.clusters.all():
                    taxonomy.clusters.add(cluster)
    except LookupError:
        # SiteBlueprintTaxonomy model doesn't exist, skip
        pass


def reverse_migrations(apps, schema_editor):
    """Reverse migration - not implemented as data loss is acceptable"""
    pass


class Migration(migrations.Migration):

    dependencies = [
        ('writer', '0003_phase1b_fix_taxonomy_relation'),
    ]

    operations = [
        migrations.RunPython(migrate_content_entity_types, reverse_migrations),
        migrations.RunPython(migrate_task_entity_types, reverse_migrations),
        migrations.RunPython(migrate_content_categories_tags_to_taxonomy, reverse_migrations),
        migrations.RunPython(migrate_blueprint_taxonomies, reverse_migrations),
    ]

