#!/usr/bin/env python
"""
Fix missing site_url in integration config
Adds site_url to config_json from site.domain or site.wp_url
"""
import os
import sys
import django

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

from igny8_core.business.integration.models import SiteIntegration
from igny8_core.auth.models import Site

def fix_integration_site_urls():
    """Add site_url to integration config if missing"""
    
    integrations = SiteIntegration.objects.filter(platform='wordpress')
    
    fixed_count = 0
    skipped_count = 0
    error_count = 0
    
    for integration in integrations:
        try:
            config = integration.config_json or {}
            
            # Check if site_url is already set
            if config.get('site_url'):
                print(f"✓ Integration {integration.id} already has site_url: {config.get('site_url')}")
                skipped_count += 1
                continue
            
            # Try to get site URL from multiple sources
            site_url = None
            
            # First, try legacy wp_url
            if integration.site.wp_url:
                site_url = integration.site.wp_url
                print(f"→ Using legacy wp_url for integration {integration.id}: {site_url}")
            
            # Fallback to domain
            elif integration.site.domain:
                site_url = integration.site.domain
                print(f"→ Using domain for integration {integration.id}: {site_url}")
            
            if site_url:
                # Update config
                config['site_url'] = site_url
                integration.config_json = config
                integration.save(update_fields=['config_json'])
                print(f"✓ Updated integration {integration.id} with site_url: {site_url}")
                fixed_count += 1
            else:
                print(f"✗ Integration {integration.id} has no site URL available (site: {integration.site.name}, id: {integration.site.id})")
                error_count += 1
        
        except Exception as e:
            print(f"✗ Error fixing integration {integration.id}: {e}")
            error_count += 1
    
    print("\n" + "="*60)
    print(f"Summary:")
    print(f"  Fixed: {fixed_count}")
    print(f"  Skipped (already set): {skipped_count}")
    print(f"  Errors: {error_count}")
    print("="*60)

if __name__ == '__main__':
    print("Fixing WordPress integration site URLs...")
    print("="*60)
    fix_integration_site_urls()

