"""
Clustering Service
Handles keyword clustering business logic
"""
import logging
from igny8_core.business.planning.models import Keywords
from igny8_core.business.billing.services.credit_service import CreditService
from igny8_core.business.billing.exceptions import InsufficientCreditsError

logger = logging.getLogger(__name__)


class ClusteringService:
    """Service for keyword clustering operations"""
    
    def __init__(self):
        self.credit_service = CreditService()
    
    def cluster_keywords(self, keyword_ids, account, sector_id=None):
        """
        Cluster keywords using AI.
        
        Args:
            keyword_ids: List of keyword IDs
            account: Account instance
            sector_id: Optional sector ID
        
        Returns:
            dict: Result with success status and data
        
        Raises:
            InsufficientCreditsError: If account doesn't have enough credits
        """
        # Validate input
        if not keyword_ids:
            return {
                'success': False,
                'error': 'No keyword IDs provided'
            }
        
        if len(keyword_ids) > 20:
            return {
                'success': False,
                'error': 'Maximum 20 keywords allowed for clustering'
            }
        
        # Check credits (fixed cost per clustering operation)
        try:
            self.credit_service.check_credits(account, 'clustering')
        except InsufficientCreditsError:
            raise
        
        # Delegate to AI task
        from igny8_core.ai.tasks import run_ai_task
        from django.conf import settings
        
        payload = {
            'ids': keyword_ids,
            'sector_id': sector_id
        }
        
        # Stage 1: When USE_SITE_BUILDER_REFACTOR is enabled, payload can include
        # taxonomy hints and dimension metadata for enhanced clustering.
        # TODO (Stage 2/3): Enhance clustering to collect and use:
        # - Taxonomy hints from SiteBlueprintTaxonomy
        # - Dimension metadata (context_type, dimension_meta) for clusters
        # - Attribute values from Keywords.attribute_values
        if getattr(settings, 'USE_SITE_BUILDER_REFACTOR', False):
            logger.info(
                f"Clustering with refactor enabled: {len(keyword_ids)} keywords, "
                f"sector_id={sector_id}, account_id={account.id}"
            )
            # Future: Add taxonomy hints and dimension metadata to payload
        
        try:
            if hasattr(run_ai_task, 'delay'):
                # Celery available - queue async
                task = run_ai_task.delay(
                    function_name='auto_cluster',
                    payload=payload,
                    account_id=account.id
                )
                return {
                    'success': True,
                    'task_id': str(task.id),
                    'message': 'Clustering started'
                }
            else:
                # Celery not available - execute synchronously
                result = run_ai_task(
                    function_name='auto_cluster',
                    payload=payload,
                    account_id=account.id
                )
                return result
        except Exception as e:
            logger.error(f"Error in cluster_keywords: {str(e)}", exc_info=True)
            return {
                'success': False,
                'error': str(e)
            }

