"""
Metadata Mapping Service
Stage 3: Persists cluster/attribute mappings from Tasks to Content
Legacy: ContentTaxonomyMap removed - taxonomy now uses Content.taxonomy_terms M2M relationship
"""
import logging
from typing import Optional
from django.db import transaction

from igny8_core.business.content.models import (
    Tasks,
    Content,
    ContentClusterMap,
    ContentAttributeMap,
)
# Removed: ContentTaxonomyMap - replaced by Content.taxonomy_terms ManyToManyField

logger = logging.getLogger(__name__)


class MetadataMappingService:
    """Service for persisting metadata mappings from Tasks to Content"""
    
    @transaction.atomic
    def persist_task_metadata_to_content(self, content: Content) -> None:
        """
        DEPRECATED: This method is deprecated as Content model no longer has task field.
        Metadata is now persisted directly on content model.
        
        Args:
            content: Content instance
        """
        logger.warning(f"[persist_task_metadata_to_content] Deprecated method called for content {content.id}")
        logger.warning(f"Content model no longer has task field - metadata should be set directly on content")
        return
    
    @transaction.atomic
    def backfill_content_metadata(self, content: Content) -> None:
        """
        Backfill metadata mappings for existing content that may be missing mappings.
        Note: task field was removed from Content model - only infers from content metadata.
        
        Args:
            content: Content instance to backfill
        """
        # If content already has mappings, skip
        if ContentClusterMap.objects.filter(content=content).exists():
            return
        
        # Try to infer from content metadata or cluster field
        if hasattr(content, 'cluster') and content.cluster:
            ContentClusterMap.objects.get_or_create(
                content=content,
                cluster=content.cluster,
                role='hub',  # Default
                defaults={
                    'account': content.account,
                    'site': content.site,
                    'sector': content.sector,
                    'source': 'manual',
                    'metadata': {},
                }
            )
            return
        
        # Fallback: Try to infer from content metadata
        if hasattr(content, 'metadata') and content.metadata:
            cluster_id = content.metadata.get('cluster_id')
            if cluster_id:
                from igny8_core.business.planning.models import Clusters
                try:
                    cluster = Clusters.objects.get(id=cluster_id)
                    ContentClusterMap.objects.get_or_create(
                        content=content,
                        cluster=cluster,
                        role='hub',  # Default
                        defaults={
                            'account': content.account,
                            'site': content.site,
                            'sector': content.sector,
                            'source': 'manual',
                            'metadata': {},
                        }
                    )
                except Clusters.DoesNotExist:
                    logger.warning(f"Cluster {cluster_id} not found for content {content.id}")

