"""
Cluster-specific validators
Shared between auto-cluster function and automation pipeline
"""
import logging
from typing import Dict, List

logger = logging.getLogger(__name__)


def validate_minimum_keywords(
    keyword_ids: List[int],
    account=None,
    min_required: int = 5
) -> Dict:
    """
    Validate that sufficient keywords are available for clustering
    
    Args:
        keyword_ids: List of keyword IDs to cluster
        account: Account object for filtering
        min_required: Minimum number of keywords required (default: 5)
    
    Returns:
        Dict with 'valid' (bool) and 'error' (str) or 'count' (int)
    """
    from igny8_core.modules.planner.models import Keywords
    
    # Build queryset
    queryset = Keywords.objects.filter(id__in=keyword_ids, status='new')
    
    if account:
        queryset = queryset.filter(account=account)
    
    # Count available keywords
    count = queryset.count()
    
    # Validate minimum
    if count < min_required:
        return {
            'valid': False,
            'error': f'Insufficient keywords for clustering. Need at least {min_required} keywords, but only {count} available.',
            'count': count,
            'required': min_required
        }
    
    return {
        'valid': True,
        'count': count,
        'required': min_required
    }


def validate_keyword_selection(
    selected_ids: List[int],
    available_count: int,
    min_required: int = 5
) -> Dict:
    """
    Validate keyword selection (for frontend validation)
    
    Args:
        selected_ids: List of selected keyword IDs
        available_count: Total count of available keywords
        min_required: Minimum required
    
    Returns:
        Dict with validation result
    """
    selected_count = len(selected_ids)
    
    # Check if any keywords selected
    if selected_count == 0:
        return {
            'valid': False,
            'error': 'No keywords selected',
            'type': 'NO_SELECTION'
        }
    
    # Check if enough selected
    if selected_count < min_required:
        return {
            'valid': False,
            'error': f'Please select at least {min_required} keywords. Currently selected: {selected_count}',
            'type': 'INSUFFICIENT_SELECTION',
            'selected': selected_count,
            'required': min_required
        }
    
    # Check if enough available (even if not all selected)
    if available_count < min_required:
        return {
            'valid': False,
            'error': f'Not enough keywords available. Need at least {min_required} keywords, but only {available_count} exist.',
            'type': 'INSUFFICIENT_AVAILABLE',
            'available': available_count,
            'required': min_required
        }
    
    return {
        'valid': True,
        'selected': selected_count,
        'available': available_count,
        'required': min_required
    }
