"""
Content Validation Service
Stage 3: Validates content metadata before publish
"""
import logging
from typing import List, Dict, Optional
from django.core.exceptions import ValidationError

from igny8_core.business.content.models import Tasks, Content

logger = logging.getLogger(__name__)


class ContentValidationService:
    """Service for validating content metadata requirements"""
    
    def validate_task(self, task: Tasks) -> List[Dict[str, str]]:
        """
        Validate a task has required metadata.
        
        Args:
            task: Task instance to validate
            
        Returns:
            List of validation errors (empty if valid)
        """
        errors = []
        
        # Stage 3: Enforce "no cluster, no task" rule when feature flag enabled
        from django.conf import settings
        if getattr(settings, 'USE_SITE_BUILDER_REFACTOR', False):
            if not task.cluster:
                errors.append({
                    'field': 'cluster',
                    'code': 'missing_cluster',
                    'message': 'Task must be associated with a cluster before content generation',
                })
        
        # Stage 3: Validate entity_type is set
        if not task.content_type:
            errors.append({
                'field': 'content_type',
                'code': 'missing_content_type',
                'message': 'Task must have a content type specified',
            })
        
        # Stage 3: Validate taxonomy for product/service entities
        if task.content_type in ['product', 'service']:
            if not task.taxonomy_term:
                errors.append({
                    'field': 'taxonomy',
                    'code': 'missing_taxonomy',
                    'message': f'{task.content_type.title()} tasks require a taxonomy association',
                })
        
        return errors
    
    def validate_content(self, content: Content) -> List[Dict[str, str]]:
        """
        Validate content has required metadata before publish.
        
        Args:
            content: Content instance to validate
            
        Returns:
            List of validation errors (empty if valid)
        """
        errors = []
        
        # Stage 3: Validate content_type
        if not content.content_type:
            errors.append({
                'field': 'content_type',
                'code': 'missing_content_type',
                'message': 'Content must have a content type specified',
            })
        
        # Stage 3: Validate cluster mapping exists for IGNY8 content
        if content.source == 'igny8':
            from igny8_core.business.content.models import ContentClusterMap
            if not ContentClusterMap.objects.filter(content=content).exists():
                errors.append({
                    'field': 'cluster_mapping',
                    'code': 'missing_cluster_mapping',
                    'message': 'Content must be mapped to at least one cluster',
                })
        
        # Stage 3: Validate taxonomy for product/service content
        if content.content_type in ['product', 'service']:
            # Check if content has taxonomy terms assigned
            if not content.taxonomy_terms.exists():
                errors.append({
                    'field': 'taxonomy_mapping',
                    'code': 'missing_taxonomy_mapping',
                    'message': f'{content.content_type.title()} content requires a taxonomy mapping',
                })
        
        # Stage 3: Validate required attributes for products
        if content.content_type == 'product':
            # Product validation - currently simplified in Stage 1
            # TODO: Re-enable attribute validation when product attributes are implemented
            pass
        
        return errors
    
    def validate_for_publish(self, content: Content) -> List[Dict[str, str]]:
        """
        Comprehensive validation before publishing content.
        
        Args:
            content: Content instance to validate
            
        Returns:
            List of validation errors (empty if ready to publish)
        """
        errors = []
        
        # Basic content validation
        errors.extend(self.validate_content(content))
        
        # Additional publish requirements
        if not content.title:
            errors.append({
                'field': 'title',
                'code': 'missing_title',
                'message': 'Content must have a title before publishing',
            })
        
        if not content.content_html or len(content.content_html.strip()) < 100:
            errors.append({
                'field': 'content_html',
                'code': 'insufficient_content',
                'message': 'Content must have at least 100 characters before publishing',
            })
        
        return errors
    
    def ensure_required_attributes(self, task: Tasks) -> List[Dict[str, str]]:
        """
        Check if task has required attributes based on entity type.
        
        Args:
            task: Task instance to check
            
        Returns:
            List of missing attribute errors
        """
        errors = []
        
        if task.content_type == 'product':
            # Products should have taxonomy and cluster
            if not task.taxonomy_term:
                errors.append({
                    'field': 'taxonomy',
                    'code': 'missing_taxonomy',
                    'message': 'Product tasks require a taxonomy (product category)',
                })
        
        return errors

