"""
Sync Metadata Service
Fetches WordPress site structure (post types, taxonomies, counts) without publishing content
"""
import logging
import requests
from typing import Dict, Any
from django.utils import timezone

from igny8_core.business.integration.models import SiteIntegration

logger = logging.getLogger(__name__)


class SyncMetadataService:
    """
    Service for syncing WordPress site metadata (counts only, no content publishing)
    """
    
    def sync_wordpress_structure(
        self,
        integration: SiteIntegration
    ) -> Dict[str, Any]:
        """
        Fetch WordPress site structure (post types, taxonomies, counts).
        Does NOT publish or sync any content.
        
        Args:
            integration: SiteIntegration instance
        
        Returns:
            dict: {
                'success': True/False,
                'post_types': {...},
                'taxonomies': {...},
                'message': '...'
            }
        """
        try:
            # Get WordPress site URL and API key
            site_url = integration.config_json.get('site_url', '')
            credentials = integration.get_credentials()
            api_key = credentials.get('api_key', '')
            
            if not site_url:
                return {
                    'success': False,
                    'error': 'Missing site_url in integration config'
                }
            
            if not api_key:
                return {
                    'success': False,
                    'error': 'Missing api_key in integration credentials'
                }
            
            # Call WordPress metadata endpoint
            metadata_url = f"{site_url}/wp-json/igny8/v1/site-metadata/"
            headers = {
                'X-IGNY8-API-Key': api_key,
                'Content-Type': 'application/json',
            }
            
            logger.info(f"[SyncMetadataService] Fetching metadata from: {metadata_url}")
            
            response = requests.get(
                metadata_url,
                headers=headers,
                timeout=30
            )
            
            if response.status_code != 200:
                logger.error(f"[SyncMetadataService] WordPress returned {response.status_code}: {response.text[:500]}")
                return {
                    'success': False,
                    'error': f'WordPress API error: {response.status_code}',
                    'details': response.text[:500]
                }
            
            # Parse response
            data = response.json()
            
            if not data.get('success'):
                return {
                    'success': False,
                    'error': data.get('error', 'Unknown error'),
                    'message': data.get('message', '')
                }
            
            metadata = data.get('data', {})
            
            # Update integration last sync time
            integration.last_sync_at = timezone.now()
            integration.sync_status = 'success'
            integration.save(update_fields=['last_sync_at', 'sync_status'])
            
            logger.info(f"[SyncMetadataService] Successfully fetched metadata:")
            logger.info(f"  - Post types: {len(metadata.get('post_types', {}))}")
            logger.info(f"  - Taxonomies: {len(metadata.get('taxonomies', {}))}")
            
            return {
                'success': True,
                'post_types': metadata.get('post_types', {}),
                'taxonomies': metadata.get('taxonomies', {}),
                'plugin_connection_enabled': metadata.get('plugin_connection_enabled', False),
                'two_way_sync_enabled': metadata.get('two_way_sync_enabled', False),
                'message': 'WordPress site structure synced successfully',
                'last_sync_at': integration.last_sync_at.isoformat()
            }
            
        except requests.exceptions.Timeout:
            logger.error(f"[SyncMetadataService] Timeout connecting to WordPress")
            integration.sync_status = 'failed'
            integration.save(update_fields=['sync_status'])
            return {
                'success': False,
                'error': 'Timeout connecting to WordPress (30s)'
            }
        except requests.exceptions.RequestException as e:
            logger.error(f"[SyncMetadataService] Request error: {str(e)}")
            integration.sync_status = 'failed'
            integration.save(update_fields=['sync_status'])
            return {
                'success': False,
                'error': f'Connection error: {str(e)}'
            }
        except Exception as e:
            logger.error(f"[SyncMetadataService] Error syncing metadata: {str(e)}", exc_info=True)
            integration.sync_status = 'failed'
            integration.save(update_fields=['sync_status'])
            return {
                'success': False,
                'error': str(e)
            }
