from django.core.management.base import BaseCommand
from django.db import connections
from noticeapp.models import NoticeUser, Listing as NoticeListing
from wordpress_integration.services import WordPressIntegrationService


class Command(BaseCommand):
    help = 'WordPress Integration Management Commands'

    def add_arguments(self, parser):
        parser.add_argument(
            'action',
            type=str,
            help='Action to perform: sync, test-connection, create-test-user, list-users'
        )
        parser.add_argument(
            '--limit',
            type=int,
            default=10,
            help='Limit number of records to process (for sync)'
        )

    def handle(self, *args, **options):
        action = options['action']
        
        if action == 'test-connection':
            self.test_connection()
        elif action == 'sync':
            self.sync_listings(options['limit'])
        elif action == 'create-test-user':
            self.create_test_user()
        elif action == 'list-users':
            self.list_users()
        else:
            self.stdout.write(
                self.style.ERROR(f'Unknown action: {action}')
            )

    def test_connection(self):
        """Test WordPress database connection"""
        self.stdout.write('Testing WordPress database connection...')
        
        try:
            wp_db = connections['wordpress']
            with wp_db.cursor() as cursor:
                cursor.execute("SELECT COUNT(*) FROM wp_posts WHERE post_type = 'listing'")
                count = cursor.fetchone()[0]
                
                self.stdout.write(
                    self.style.SUCCESS(f'✅ WordPress connection successful!')
                )
                self.stdout.write(f'Found {count} existing listings in WordPress.')
                
        except Exception as e:
            self.stdout.write(
                self.style.ERROR(f'❌ WordPress connection failed: {str(e)}')
            )

    def sync_listings(self, limit):
        """Sync NoticeApp listings to WordPress"""
        self.stdout.write(f'Syncing up to {limit} NoticeApp listings to WordPress...')
        
        wp_service = WordPressIntegrationService()
        synced_count = 0
        errors = []
        
        # Get NoticeListings without wp_listing_id
        notice_listings = NoticeListing.objects.filter(
            wp_listing_id__isnull=True
        )[:limit]
        
        total_count = notice_listings.count()
        self.stdout.write(f'Found {total_count} listings to sync.')
        
        for i, notice_listing in enumerate(notice_listings, 1):
            try:
                self.stdout.write(f'Processing {i}/{total_count}: {notice_listing.title}')
                
                # Get or create WordPress user
                try:
                    notice_user = NoticeUser.objects.first()
                    if not notice_user:
                        notice_user = NoticeUser.objects.create(
                            email='admin@noticeboard.co.zw',
                            password_hash='admin_hash',
                            display_name='Admin User'
                        )
                except Exception as e:
                    errors.append(f"User creation failed for listing {notice_listing.id}: {str(e)}")
                    continue
                
                # Prepare listing data
                listing_data = {
                    'title': notice_listing.title or 'Untitled Listing',
                    'description': notice_listing.description_html or notice_listing.description_text or '',
                    'tagline': notice_listing.tagline or '',
                    'phone': notice_listing.phone or '',
                    'website': notice_listing.website or '',
                    'address': notice_listing.location or '',
                    'social_networks': notice_listing.socials_json or {},
                    'gallery': notice_listing.gallery_json or [],
                    'post_type': notice_listing.post_type or 'listing',
                    'plan_id': 1
                }
                
                # Create WordPress listing
                result = wp_service.create_listing_from_noticeapp(notice_user, listing_data)
                
                if result['success']:
                    # Update NoticeListing with wp_listing_id
                    notice_listing.wp_listing_id = result['wp_listing_id']
                    notice_listing.save()
                    synced_count += 1
                    self.stdout.write(f'  ✅ Synced to WordPress ID: {result["wp_listing_id"]}')
                else:
                    errors.append(f"Failed to sync listing {notice_listing.id}: {result['error']}")
                    self.stdout.write(f'  ❌ Failed: {result["error"]}')
                    
            except Exception as e:
                errors.append(f"Error syncing listing {notice_listing.id}: {str(e)}")
                self.stdout.write(f'  ❌ Error: {str(e)}')
        
        # Summary
        self.stdout.write('\n' + '='*50)
        self.stdout.write(f'✅ Successfully synced: {synced_count} listings')
        self.stdout.write(f'❌ Errors: {len(errors)}')
        
        if errors:
            self.stdout.write('\nErrors:')
            for error in errors[:5]:  # Show first 5 errors
                self.stdout.write(f'  - {error}')
            if len(errors) > 5:
                self.stdout.write(f'  ... and {len(errors) - 5} more errors')

    def create_test_user(self):
        """Create a test WordPress user"""
        self.stdout.write('Creating test WordPress user...')
        
        try:
            # Create test NoticeUser
            test_user, created = NoticeUser.objects.get_or_create(
                email='test@wordpress-integration.co.zw',
                defaults={
                    'password_hash': 'test_hash_123',
                    'display_name': 'Test WordPress User'
                }
            )
            
            if created:
                self.stdout.write('✅ Test NoticeUser created')
            else:
                self.stdout.write('ℹ️  Test NoticeUser already exists')
            
            # Create WordPress user
            wp_service = WordPressIntegrationService()
            wp_user_id = wp_service.user_manager.get_or_create_wp_user(test_user)
            
            self.stdout.write(
                self.style.SUCCESS(f'✅ WordPress user created/found with ID: {wp_user_id}')
            )
            
        except Exception as e:
            self.stdout.write(
                self.style.ERROR(f'❌ Test user creation failed: {str(e)}')
            )

    def list_users(self):
        """List WordPress users"""
        self.stdout.write('Listing WordPress users...')
        
        try:
            wp_db = connections['wordpress']
            with wp_db.cursor() as cursor:
                cursor.execute("""
                    SELECT ID, user_login, user_email, display_name, user_registered
                    FROM wp_users 
                    ORDER BY user_registered DESC 
                    LIMIT 10
                """)
                
                users = cursor.fetchall()
                
                if users:
                    self.stdout.write(f'Found {len(users)} WordPress users:')
                    self.stdout.write('ID | Login | Email | Display Name | Registered')
                    self.stdout.write('-' * 80)
                    
                    for user in users:
                        self.stdout.write(f'{user[0]:3} | {user[1]:15} | {user[2]:25} | {user[3]:15} | {user[4]}')
                else:
                    self.stdout.write('No WordPress users found.')
                    
        except Exception as e:
            self.stdout.write(
                self.style.ERROR(f'❌ Failed to list users: {str(e)}')
            )
