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

Manages site integrations (WordPress, Shopify, etc.).
"""
import logging
from typing import Optional, Dict, Any

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

logger = logging.getLogger(__name__)


class IntegrationService:
    """
    Service for managing site integrations.
    """
    
    def create_integration(
        self,
        site: Site,
        platform: str,
        config: Dict[str, Any],
        credentials: Dict[str, Any],
        platform_type: str = 'cms'
    ) -> SiteIntegration:
        """
        Create a new site integration.
        
        Args:
            site: Site instance
            platform: Platform name ('wordpress', 'shopify', 'custom')
            config: Platform-specific configuration
            credentials: Platform credentials (will be encrypted)
            platform_type: Platform type ('cms', 'ecommerce', 'custom_api')
        
        Returns:
            SiteIntegration instance
        """
        integration = SiteIntegration.objects.create(
            account=site.account,
            site=site,
            platform=platform,
            platform_type=platform_type,
            config_json=config,
            credentials_json=credentials,
            is_active=True
        )
        
        logger.info(
            f"[IntegrationService] Created integration {integration.id} for site {site.id}, platform {platform}"
        )
        
        return integration
    
    def update_integration(
        self,
        integration: SiteIntegration,
        config: Optional[Dict[str, Any]] = None,
        credentials: Optional[Dict[str, Any]] = None,
        is_active: Optional[bool] = None
    ) -> SiteIntegration:
        """
        Update an existing integration.
        
        Args:
            integration: SiteIntegration instance
            config: Updated configuration (optional)
            credentials: Updated credentials (optional)
            is_active: Active status (optional)
        
        Returns:
            Updated SiteIntegration instance
        """
        if config is not None:
            integration.config_json = config
        
        if credentials is not None:
            integration.set_credentials(credentials)
        
        if is_active is not None:
            integration.is_active = is_active
        
        integration.save()
        
        logger.info(f"[IntegrationService] Updated integration {integration.id}")
        
        return integration
    
    def delete_integration(self, integration: SiteIntegration):
        """
        Delete an integration.
        
        Args:
            integration: SiteIntegration instance
        """
        integration_id = integration.id
        integration.delete()
        
        logger.info(f"[IntegrationService] Deleted integration {integration_id}")
    
    def get_integration(
        self,
        site: Site,
        platform: str
    ) -> Optional[SiteIntegration]:
        """
        Get integration for a site and platform.
        
        Args:
            site: Site instance
            platform: Platform name
        
        Returns:
            SiteIntegration or None
        """
        return SiteIntegration.objects.filter(
            site=site,
            platform=platform,
            is_active=True
        ).first()
    
    def list_integrations(
        self,
        site: Site,
        active_only: bool = True
    ) -> list:
        """
        List all integrations for a site.
        
        Args:
            site: Site instance
            active_only: Only return active integrations
        
        Returns:
            List of SiteIntegration instances
        """
        queryset = SiteIntegration.objects.filter(site=site)
        
        if active_only:
            queryset = queryset.filter(is_active=True)
        
        return list(queryset.order_by('-created_at'))
    
    def get_integrations_for_site(
        self,
        site: Site
    ):
        """
        Get integrations for a site (alias for list_integrations for compatibility).
        
        Args:
            site: Site instance
        
        Returns:
            QuerySet of SiteIntegration instances
        """
        return SiteIntegration.objects.filter(site=site, is_active=True)
    
    def test_connection(
        self,
        integration: SiteIntegration,
        is_initial_connection: bool = False
    ) -> Dict[str, Any]:
        """
        Test connection to the integrated platform.
        
        Args:
            integration: SiteIntegration instance
            is_initial_connection: If True, allows connection test to pass even if WordPress
                                  plugin hasn't stored API key yet (for initial setup)
        
        Returns:
            dict: {
                'success': bool,
                'message': str,
                'details': dict
            }
        
        Raises:
            NotImplementedError: For platforms that don't have connection testing implemented
        """
        try:
            if integration.platform == 'wordpress':
                return self._test_wordpress_connection(integration, is_initial_connection=is_initial_connection)
            elif integration.platform == 'shopify':
                return self._test_shopify_connection(integration)
            else:
                raise NotImplementedError(f'Connection testing not implemented for platform: {integration.platform}')
        except NotImplementedError:
            raise
        except Exception as e:
            logger.error(
                f"[IntegrationService] Error testing connection for integration {integration.id}: {str(e)}",
                exc_info=True
            )
            return {
                'success': False,
                'message': str(e),
                'details': {}
            }
    
    def _test_wordpress_connection(
        self,
        integration: SiteIntegration,
        is_initial_connection: bool = False
    ) -> Dict[str, Any]:
        """
        Test WordPress connection using API key only.
        
        Args:
            integration: SiteIntegration instance
        
        Returns:
            dict: Connection test result with detailed health status
        """
        import requests
        
        config = integration.config_json
        
        # Try to get site URL from multiple sources
        site_url = config.get('site_url')
        
        # Fallback to legacy wp_url if available
        if not site_url and integration.site.wp_url:
            site_url = integration.site.wp_url
            logger.info(f"[IntegrationService] Using legacy wp_url for integration {integration.id}: {site_url}")
        
        # Fallback to domain field
        if not site_url and integration.site.domain:
            site_url = integration.site.domain
            logger.info(f"[IntegrationService] Using domain for integration {integration.id}: {site_url}")
        
        if not site_url:
            return {
                'success': False,
                'message': 'WordPress site URL not configured.',
                'details': {
                    'integration_id': integration.id,
                    'site_id': integration.site.id,
                    'site_name': integration.site.name,
                }
            }
        
        # Get API key from site
        api_key = integration.site.wp_api_key
        
        if not api_key:
            return {
                'success': False,
                'message': 'API key not configured.',
                'details': {}
            }
        
        # Initialize health check results
        health_checks = {
            'site_url_configured': True,
            'api_key_configured': True,
            'wp_rest_api_reachable': False,
            'plugin_installed': False,
            'plugin_has_api_key': False,
        }
        
        issues = []
        
        try:
            # Check 1: WordPress REST API reachable (public endpoint)
            try:
                rest_response = requests.get(
                    f"{site_url.rstrip('/')}/wp-json/",
                    timeout=10
                )
                if rest_response.status_code == 200:
                    health_checks['wp_rest_api_reachable'] = True
                    logger.info(f"[IntegrationService] ✓ WordPress REST API reachable: {site_url}")
                else:
                    issues.append(f"WordPress REST API not reachable: HTTP {rest_response.status_code}")
            except Exception as e:
                issues.append(f"WordPress REST API unreachable: {str(e)}")
            
            # Check 2: IGNY8 Plugin installed and has API key configured
            try:
                status_response = requests.get(
                    f"{site_url.rstrip('/')}/wp-json/igny8/v1/status",
                    timeout=10
                )
                if status_response.status_code == 200:
                    health_checks['plugin_installed'] = True
                    logger.info(f"[IntegrationService] ✓ IGNY8 plugin installed")
                    
                    status_data = status_response.json()
                    # Plugin returns unified format: {success: true, data: {...}}
                    # Extract data from unified response format
                    plugin_data = status_data.get('data', status_data)  # Fallback to direct access for legacy
                    
                    if plugin_data.get('connected') or plugin_data.get('has_api_key'):
                        health_checks['plugin_has_api_key'] = True
                        logger.info(f"[IntegrationService] ✓ Plugin has API key configured")
                    else:
                        issues.append("Plugin installed but not configured with API key")
                else:
                    issues.append(f"IGNY8 plugin not found: HTTP {status_response.status_code}")
            except Exception as e:
                issues.append(f"Cannot detect IGNY8 plugin: {str(e)}")
            
            # Success determination
            # For initial connection, we don't require plugin_has_api_key yet
            # because WordPress hasn't stored it yet - that's what we're testing!
            # For subsequent health checks, we require all checks to pass
            if is_initial_connection:
                is_healthy = (
                    health_checks['api_key_configured'] and
                    health_checks['wp_rest_api_reachable'] and
                    health_checks['plugin_installed']
                )
            else:
                is_healthy = (
                    health_checks['api_key_configured'] and
                    health_checks['wp_rest_api_reachable'] and
                    health_checks['plugin_installed'] and
                    health_checks['plugin_has_api_key']
                )
            
            # Save site_url to config if successful and not already set
            if is_healthy and not config.get('site_url'):
                config['site_url'] = site_url
                integration.config_json = config
                integration.save(update_fields=['config_json'])
                logger.info(f"[IntegrationService] Saved site_url to integration {integration.id} config: {site_url}")
            
            # Build response message
            if is_healthy:
                message = "✅ WordPress integration is connected and authenticated via API key"
            elif not health_checks['wp_rest_api_reachable']:
                message = "❌ Cannot reach WordPress site"
            elif not health_checks['plugin_installed']:
                message = "⚠️ WordPress is reachable but IGNY8 plugin not installed"
            elif not health_checks['plugin_has_api_key']:
                if is_initial_connection:
                    # During initial connection, this is expected - WordPress will store the key after successful test
                    message = "✅ WordPress integration ready - API key will be stored after connection"
                else:
                    message = "⚠️ Plugin is installed but API key not configured in WordPress"
            else:
                message = "❌ WordPress connection failed"
            
            return {
                'success': is_healthy,
                'fully_functional': is_healthy,
                'message': message,
                'site_url': site_url,
                'health_checks': health_checks,
                'issues': issues if issues else None,
                'details': {
                    'last_sync': str(integration.last_sync_at) if integration.last_sync_at else None,
                    'integration_active': integration.is_active,
                }
            }
            
        except Exception as e:
            logger.error(f"WordPress connection test failed: {e}")
            return {
                'success': False,
                'fully_functional': False,
                'message': f'Connection test failed: {str(e)}',
                'site_url': site_url,
                'health_checks': health_checks,
                'issues': issues + [str(e)],
                'details': {
                    'error': str(e)
                }
            }
    
    def _test_shopify_connection(
        self,
        integration: SiteIntegration
    ) -> Dict[str, Any]:
        """
        Test Shopify connection.
        
        Args:
            integration: SiteIntegration instance
        
        Returns:
            dict: Connection test result
        """
        # TODO: Implement Shopify connection testing
        return {
            'success': False,
            'message': 'Shopify connection testing not yet implemented',
            'details': {}
        }

