"""
Ideas Service
Handles content ideas generation business logic
"""
import logging
from igny8_core.business.planning.models import Clusters
from igny8_core.business.billing.services.credit_service import CreditService
from igny8_core.business.billing.exceptions import InsufficientCreditsError

logger = logging.getLogger(__name__)


class IdeasService:
    """Service for content ideas generation operations"""
    
    def __init__(self):
        self.credit_service = CreditService()
    
    def generate_ideas(self, cluster_ids, account):
        """
        Generate content ideas from clusters.
        
        Args:
            cluster_ids: List of cluster IDs
            account: Account instance
        
        Returns:
            dict: Result with success status and data
        
        Raises:
            InsufficientCreditsError: If account doesn't have enough credits
        """
        # Validate input
        if not cluster_ids:
            return {
                'success': False,
                'error': 'No cluster IDs provided'
            }
        
        if len(cluster_ids) > 10:
            return {
                'success': False,
                'error': 'Maximum 10 clusters allowed for idea generation'
            }
        
        # Get clusters to count ideas
        clusters = Clusters.objects.filter(id__in=cluster_ids, account=account)
        idea_count = len(cluster_ids)
        
        # Check credits
        try:
            self.credit_service.check_credits(account, 'idea_generation', idea_count)
        except InsufficientCreditsError:
            raise
        
        # Delegate to AI task
        from igny8_core.ai.tasks import run_ai_task
        
        payload = {
            'ids': cluster_ids
        }
        
        try:
            if hasattr(run_ai_task, 'delay'):
                # Celery available - queue async
                task = run_ai_task.delay(
                    function_name='auto_generate_ideas',
                    payload=payload,
                    account_id=account.id
                )
                return {
                    'success': True,
                    'task_id': str(task.id),
                    'message': 'Idea generation started'
                }
            else:
                # Celery not available - execute synchronously
                result = run_ai_task(
                    function_name='auto_generate_ideas',
                    payload=payload,
                    account_id=account.id
                )
                return result
        except Exception as e:
            logger.error(f"Error in generate_ideas: {str(e)}", exc_info=True)
            return {
                'success': False,
                'error': str(e)
            }

