"""
Sync Service
Phase 6: Site Integration & Multi-Destination Publishing

Handles two-way synchronization between IGNY8 and external platforms.
"""
import logging
from typing import Dict, Any, Optional
from datetime import datetime

from igny8_core.business.integration.models import SiteIntegration

logger = logging.getLogger(__name__)


class SyncService:
    """
    Service for handling two-way sync between IGNY8 and external platforms.
    """
    
    def sync(
        self,
        integration: SiteIntegration,
        direction: str = 'both',
        content_types: Optional[list] = None
    ) -> Dict[str, Any]:
        """
        Perform synchronization.
        Stage 4: Enhanced to record sync runs for health tracking.
        
        Args:
            integration: SiteIntegration instance
            direction: 'both', 'to_external', 'from_external'
            content_types: List of content types to sync (optional, syncs all if None)
        
        Returns:
            dict: Sync result
        """
        if not integration.sync_enabled:
            return {
                'success': False,
                'message': 'Sync is not enabled for this integration',
                'synced_count': 0
            }
        
        # Update sync status
        integration.sync_status = 'syncing'
        integration.save(update_fields=['sync_status', 'updated_at'])
        
        try:
            if direction in ('both', 'to_external'):
                # Sync from IGNY8 to external platform
                to_result = self._sync_to_external(integration, content_types)
            else:
                to_result = {'success': True, 'synced_count': 0}
            
            if direction in ('both', 'from_external'):
                # Sync from external platform to IGNY8
                from_result = self._sync_from_external(integration, content_types)
            else:
                from_result = {'success': True, 'synced_count': 0}
            
            # Update sync status
            if to_result.get('success') and from_result.get('success'):
                integration.sync_status = 'success'
                integration.sync_error = None
            else:
                integration.sync_status = 'failed'
                integration.sync_error = (
                    to_result.get('error', '') + ' ' + from_result.get('error', '')
                ).strip()
            
            integration.last_sync_at = datetime.now()
            integration.save(update_fields=['sync_status', 'sync_error', 'last_sync_at', 'updated_at'])
            
            total_synced = to_result.get('synced_count', 0) + from_result.get('synced_count', 0)
            
            result = {
                'success': to_result.get('success') and from_result.get('success'),
                'synced_count': total_synced,
                'to_external': to_result,
                'from_external': from_result
            }
            
            # Stage 4: Record sync run for health tracking
            try:
                from igny8_core.business.integration.services.sync_health_service import SyncHealthService
                sync_health_service = SyncHealthService()
                sync_health_service.record_sync_run(integration.id, result)
            except Exception as e:
                logger.warning(f"Failed to record sync run: {e}")
            
            return result
            
        except Exception as e:
            logger.error(
                f"[SyncService] Error syncing integration {integration.id}: {str(e)}",
                exc_info=True
            )
            
            integration.sync_status = 'failed'
            integration.sync_error = str(e)
            integration.save(update_fields=['sync_status', 'sync_error', 'updated_at'])
            
            error_result = {
                'success': False,
                'error': str(e),
                'synced_count': 0
            }
            
            # Stage 4: Record failed sync run
            try:
                from igny8_core.business.integration.services.sync_health_service import SyncHealthService
                sync_health_service = SyncHealthService()
                sync_health_service.record_sync_run(integration.id, error_result)
            except Exception as e:
                logger.warning(f"Failed to record sync run: {e}")
            
            return error_result
    
    def _sync_to_external(
        self,
        integration: SiteIntegration,
        content_types: Optional[list] = None
    ) -> Dict[str, Any]:
        """
        Sync content from IGNY8 to external platform.
        
        Args:
            integration: SiteIntegration instance
            content_types: List of content types to sync
        
        Returns:
            dict: Sync result
        """
        # This will be implemented by ContentSyncService
        from igny8_core.business.integration.services.content_sync_service import ContentSyncService
        
        sync_service = ContentSyncService()
        return sync_service.sync_to_external(integration, content_types)
    
    def _sync_from_external(
        self,
        integration: SiteIntegration,
        content_types: Optional[list] = None
    ) -> Dict[str, Any]:
        """
        Sync content from external platform to IGNY8.
        
        Args:
            integration: SiteIntegration instance
            content_types: List of content types to sync
        
        Returns:
            dict: Sync result
        """
        # This will be implemented by ContentSyncService
        from igny8_core.business.integration.services.content_sync_service import ContentSyncService
        
        sync_service = ContentSyncService()
        return sync_service.sync_from_external(integration, content_types)
    
    def get_sync_status(
        self,
        integration: SiteIntegration
    ) -> Dict[str, Any]:
        """
        Get current sync status for an integration.
        
        Args:
            integration: SiteIntegration instance
        
        Returns:
            dict: Sync status information
        """
        return {
            'sync_enabled': integration.sync_enabled,
            'sync_status': integration.sync_status,
            'last_sync_at': integration.last_sync_at.isoformat() if integration.last_sync_at else None,
            'sync_error': integration.sync_error
        }

