"""
Content Generation Service
Handles content generation business logic
"""
import logging
from igny8_core.business.content.models import Tasks
from igny8_core.business.billing.services.credit_service import CreditService
from igny8_core.business.billing.exceptions import InsufficientCreditsError

logger = logging.getLogger(__name__)


class ContentGenerationService:
    """Service for content generation operations"""
    
    def __init__(self):
        self.credit_service = CreditService()
    
    def generate_content(self, task_ids, account):
        """
        Generate content for tasks.
        
        Args:
            task_ids: List of task IDs
            account: Account instance
        
        Returns:
            dict: Result with success status and data
        
        Raises:
            InsufficientCreditsError: If account doesn't have enough credits
        """
        # Get tasks
        tasks = Tasks.objects.filter(id__in=task_ids, account=account)
        
        # Calculate estimated credits needed based on word count
        total_word_count = sum(task.word_count or 1000 for task in tasks)
        
        # Check credits
        try:
            self.credit_service.check_credits(account, 'content_generation', total_word_count)
        except InsufficientCreditsError:
            raise
        
        # Delegate to AI task (actual generation happens in Celery)
        from igny8_core.ai.tasks import run_ai_task
        
        try:
            if hasattr(run_ai_task, 'delay'):
                # Celery available - queue async
                task = run_ai_task.delay(
                    function_name='generate_content',
                    payload={'ids': task_ids},
                    account_id=account.id
                )
                return {
                    'success': True,
                    'task_id': str(task.id),
                    'message': 'Content generation started'
                }
            else:
                # Celery not available - execute synchronously
                result = run_ai_task(
                    function_name='generate_content',
                    payload={'ids': task_ids},
                    account_id=account.id
                )
                return result
        except Exception as e:
            logger.error(f"Error in generate_content: {str(e)}", exc_info=True)
            return {
                'success': False,
                'error': str(e)
            }
    
    def generate_product_content(self, product_data, account, site=None, sector=None):
        """
        Generate product content.
        
        Args:
            product_data: Dict with product information (name, description, features, etc.)
            account: Account instance
            site: Site instance (optional)
            sector: Sector instance (optional)
        
        Returns:
            dict: Result with success status and data
        
        Raises:
            InsufficientCreditsError: If account doesn't have enough credits
        """
        # Calculate estimated credits needed (default 1500 words for product content)
        estimated_word_count = product_data.get('word_count', 1500)
        
        # Check credits
        try:
            self.credit_service.check_credits(account, 'content_generation', estimated_word_count)
        except InsufficientCreditsError:
            raise
        
        # Delegate to AI task
        from igny8_core.ai.tasks import run_ai_task
        
        try:
            payload = {
                'product_name': product_data.get('name', ''),
                'product_description': product_data.get('description', ''),
                'product_features': product_data.get('features', []),
                'target_audience': product_data.get('target_audience', ''),
                'primary_keyword': product_data.get('primary_keyword', ''),
                'site_id': site.id if site else None,
                'sector_id': sector.id if sector else None,
            }
            
            if hasattr(run_ai_task, 'delay'):
                # Celery available - queue async
                task = run_ai_task.delay(
                    function_name='generate_product_content',
                    payload=payload,
                    account_id=account.id
                )
                return {
                    'success': True,
                    'task_id': str(task.id),
                    'message': 'Product content generation started'
                }
            else:
                # Celery not available - execute synchronously
                result = run_ai_task(
                    function_name='generate_product_content',
                    payload=payload,
                    account_id=account.id
                )
                return result
        except Exception as e:
            logger.error(f"Error in generate_product_content: {str(e)}", exc_info=True)
            return {
                'success': False,
                'error': str(e)
            }
    
    def generate_service_page(self, service_data, account, site=None, sector=None):
        """
        Generate service page content.
        
        Args:
            service_data: Dict with service information (name, description, benefits, etc.)
            account: Account instance
            site: Site instance (optional)
            sector: Sector instance (optional)
        
        Returns:
            dict: Result with success status and data
        
        Raises:
            InsufficientCreditsError: If account doesn't have enough credits
        """
        # Calculate estimated credits needed (default 1800 words for service page)
        estimated_word_count = service_data.get('word_count', 1800)
        
        # Check credits
        try:
            self.credit_service.check_credits(account, 'content_generation', estimated_word_count)
        except InsufficientCreditsError:
            raise
        
        # Delegate to AI task
        from igny8_core.ai.tasks import run_ai_task
        
        try:
            payload = {
                'service_name': service_data.get('name', ''),
                'service_description': service_data.get('description', ''),
                'service_benefits': service_data.get('benefits', []),
                'target_audience': service_data.get('target_audience', ''),
                'primary_keyword': service_data.get('primary_keyword', ''),
                'site_id': site.id if site else None,
                'sector_id': sector.id if sector else None,
            }
            
            if hasattr(run_ai_task, 'delay'):
                # Celery available - queue async
                task = run_ai_task.delay(
                    function_name='generate_service_page',
                    payload=payload,
                    account_id=account.id
                )
                return {
                    'success': True,
                    'task_id': str(task.id),
                    'message': 'Service page generation started'
                }
            else:
                # Celery not available - execute synchronously
                result = run_ai_task(
                    function_name='generate_service_page',
                    payload=payload,
                    account_id=account.id
                )
                return result
        except Exception as e:
            logger.error(f"Error in generate_service_page: {str(e)}", exc_info=True)
            return {
                'success': False,
                'error': str(e)
            }
    
    def generate_taxonomy(self, taxonomy_data, account, site=None, sector=None):
        """
        Generate taxonomy page content.
        
        Args:
            taxonomy_data: Dict with taxonomy information (name, description, items, etc.)
            account: Account instance
            site: Site instance (optional)
            sector: Sector instance (optional)
        
        Returns:
            dict: Result with success status and data
        
        Raises:
            InsufficientCreditsError: If account doesn't have enough credits
        """
        # Calculate estimated credits needed (default 1200 words for taxonomy page)
        estimated_word_count = taxonomy_data.get('word_count', 1200)
        
        # Check credits
        try:
            self.credit_service.check_credits(account, 'content_generation', estimated_word_count)
        except InsufficientCreditsError:
            raise
        
        # Delegate to AI task
        from igny8_core.ai.tasks import run_ai_task
        
        try:
            payload = {
                'taxonomy_name': taxonomy_data.get('name', ''),
                'taxonomy_description': taxonomy_data.get('description', ''),
                'taxonomy_items': taxonomy_data.get('items', []),
                'primary_keyword': taxonomy_data.get('primary_keyword', ''),
                'site_id': site.id if site else None,
                'sector_id': sector.id if sector else None,
            }
            
            if hasattr(run_ai_task, 'delay'):
                # Celery available - queue async
                task = run_ai_task.delay(
                    function_name='generate_taxonomy',
                    payload=payload,
                    account_id=account.id
                )
                return {
                    'success': True,
                    'task_id': str(task.id),
                    'message': 'Taxonomy generation started'
                }
            else:
                # Celery not available - execute synchronously
                result = run_ai_task(
                    function_name='generate_taxonomy',
                    payload=payload,
                    account_id=account.id
                )
                return result
        except Exception as e:
            logger.error(f"Error in generate_taxonomy: {str(e)}", exc_info=True)
            return {
                'success': False,
                'error': str(e)
            }

