#!/usr/bin/env python
"""
Fix missing taxonomy relationships for existing content
This script will:
1. Find content that should have tags/categories based on their keywords
2. Create appropriate taxonomy terms
3. Link them to the content
"""
import os
import sys
import django

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'igny8_core.settings')
django.setup()

from django.db import transaction
from django.utils.text import slugify
from igny8_core.business.content.models import Content, ContentTaxonomy

print("=" * 80)
print("FIXING MISSING TAXONOMY RELATIONSHIPS")
print("=" * 80)

# Get all content without taxonomy terms
content_without_tags = Content.objects.filter(taxonomy_terms__isnull=True).distinct()
print(f"\nFound {content_without_tags.count()} content items without tags/categories")

fixed_count = 0
for content in content_without_tags:
    print(f"\nProcessing Content #{content.id}: {content.title[:50]}...")
    
    # Generate tags from keywords
    tags_to_add = []
    categories_to_add = []
    
    # Use primary keyword as a tag
    if content.primary_keyword:
        tags_to_add.append(content.primary_keyword)
    
    # Use secondary keywords as tags
    if content.secondary_keywords and isinstance(content.secondary_keywords, list):
        tags_to_add.extend(content.secondary_keywords[:3])  # Limit to 3
    
    # Create category based on cluster only
    if content.cluster:
        categories_to_add.append(content.cluster.name)
    
    with transaction.atomic():
        # Process tags
        for tag_name in tags_to_add:
            if tag_name and isinstance(tag_name, str):
                tag_name = tag_name.strip()
                if tag_name:
                    try:
                        tag_obj, created = ContentTaxonomy.objects.get_or_create(
                            site=content.site,
                            name=tag_name,
                            taxonomy_type='tag',
                            defaults={
                                'slug': slugify(tag_name),
                                'sector': content.sector,
                                'account': content.account,
                                'description': '',
                                'external_taxonomy': '',
                                'sync_status': '',
                                'count': 0,
                                'metadata': {},
                            }
                        )
                        content.taxonomy_terms.add(tag_obj)
                        print(f"  + Tag: {tag_name} ({'created' if created else 'existing'})")
                    except Exception as e:
                        print(f"  ✗ Failed to add tag '{tag_name}': {e}")
        
        # Process categories
        for category_name in categories_to_add:
            if category_name and isinstance(category_name, str):
                category_name = category_name.strip()
                if category_name:
                    try:
                        category_obj, created = ContentTaxonomy.objects.get_or_create(
                            site=content.site,
                            name=category_name,
                            taxonomy_type='category',
                            defaults={
                                'slug': slugify(category_name),
                                'sector': content.sector,
                                'account': content.account,
                                'description': '',
                                'external_taxonomy': '',
                                'sync_status': '',
                                'count': 0,
                                'metadata': {},
                            }
                        )
                        content.taxonomy_terms.add(category_obj)
                        print(f"  + Category: {category_name} ({'created' if created else 'existing'})")
                    except Exception as e:
                        print(f"  ✗ Failed to add category '{category_name}': {e}")
    
    fixed_count += 1

print("\n" + "=" * 80)
print(f"FIXED {fixed_count} CONTENT ITEMS")
print("=" * 80)
