#!/usr/bin/env python
"""
Verify Tags and Categories Implementation
Tests that ContentTaxonomy integration is working correctly
"""
import os
import sys
import django

# Add the backend directory to the path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'igny8_core.settings')
django.setup()

from igny8_core.business.content.models import Content, ContentTaxonomy
from igny8_core.modules.writer.serializers import ContentSerializer

print("=" * 80)
print("VERIFYING TAGS AND CATEGORIES IMPLEMENTATION")
print("=" * 80)

# Check if ContentTaxonomy model is accessible
print("\n1. ContentTaxonomy Model Check:")
try:
    taxonomy_count = ContentTaxonomy.objects.count()
    print(f"   ✓ ContentTaxonomy model accessible")
    print(f"   ✓ Total taxonomy terms in database: {taxonomy_count}")
    
    # Show breakdown by type
    tag_count = ContentTaxonomy.objects.filter(taxonomy_type='tag').count()
    category_count = ContentTaxonomy.objects.filter(taxonomy_type='category').count()
    print(f"   - Tags: {tag_count}")
    print(f"   - Categories: {category_count}")
except Exception as e:
    print(f"   ✗ Error accessing ContentTaxonomy: {e}")
    sys.exit(1)

# Check Content model has taxonomy_terms field
print("\n2. Content Model Taxonomy Field Check:")
try:
    content = Content.objects.first()
    if content:
        taxonomy_terms = content.taxonomy_terms.all()
        print(f"   ✓ Content.taxonomy_terms field accessible")
        print(f"   ✓ Sample content (ID: {content.id}) has {taxonomy_terms.count()} taxonomy terms")
        for term in taxonomy_terms:
            print(f"     - {term.name} ({term.taxonomy_type})")
    else:
        print("   ⚠ No content found in database")
except Exception as e:
    print(f"   ✗ Error accessing Content.taxonomy_terms: {e}")
    sys.exit(1)

# Check serializer includes tags and categories
print("\n3. ContentSerializer Tags/Categories Check:")
try:
    if content:
        serializer = ContentSerializer(content)
        data = serializer.data
        
        # Check if fields exist
        has_tags_field = 'tags' in data
        has_categories_field = 'categories' in data
        has_taxonomy_data = 'taxonomy_terms_data' in data
        
        print(f"   ✓ Serializer includes 'tags' field: {has_tags_field}")
        print(f"   ✓ Serializer includes 'categories' field: {has_categories_field}")
        print(f"   ✓ Serializer includes 'taxonomy_terms_data' field: {has_taxonomy_data}")
        
        if has_tags_field:
            print(f"   - Tags: {data.get('tags', [])}")
        if has_categories_field:
            print(f"   - Categories: {data.get('categories', [])}")
        
    else:
        print("   ⚠ No content to serialize")
except Exception as e:
    print(f"   ✗ Error serializing content: {e}")
    import traceback
    traceback.print_exc()
    sys.exit(1)

# Check if we can create taxonomy terms
print("\n4. Creating Test Taxonomy Terms:")
try:
    from django.utils.text import slugify
    
    # Try to create a test tag
    test_tag, created = ContentTaxonomy.objects.get_or_create(
        name="Test Tag",
        taxonomy_type='tag',
        defaults={
            'slug': slugify("Test Tag"),
        }
    )
    if created:
        print(f"   ✓ Created new test tag: {test_tag.name}")
    else:
        print(f"   ✓ Test tag already exists: {test_tag.name}")
    
    # Try to create a test category
    test_category, created = ContentTaxonomy.objects.get_or_create(
        name="Test Category",
        taxonomy_type='category',
        defaults={
            'slug': slugify("Test Category"),
        }
    )
    if created:
        print(f"   ✓ Created new test category: {test_category.name}")
    else:
        print(f"   ✓ Test category already exists: {test_category.name}")
    
except Exception as e:
    print(f"   ✗ Error creating taxonomy terms: {e}")
    import traceback
    traceback.print_exc()
    sys.exit(1)

print("\n" + "=" * 80)
print("VERIFICATION COMPLETE")
print("=" * 80)
print("\nNext steps:")
print("1. Access Django admin at /admin/writer/contenttaxonomy/")
print("2. Generate content via AI and check if tags/categories are saved")
print("3. Check API response includes 'tags' and 'categories' fields")
print("=" * 80)
