"""Tags-only allocation service for metadata stage."""

import polars as pl
from ..config import KeyConfig
from .random_service import DeterministicRandomService


class TagsAllocationService:
    """Service for tags_only=true scenario - all resources get tag columns."""

    def __init__(self, random_service: DeterministicRandomService):
        """Initialize with deterministic random service for consistent allocation."""
        self.random_service = random_service

    def allocate_tags_to_all_resources(
        self,
        df: pl.DataFrame,
        key_config: KeyConfig,
        provider: str
    ) -> pl.DataFrame:
        """
        Allocate tag column to ALL resources in the DataFrame.

        Args:
            df: DataFrame with resources to tag
            key_config: Key configuration with values to allocate
            provider: Provider name for column naming (will be normalized)

        Returns:
            DataFrame with new resource/tag:{provider}:{key} column added
        """
        if df.height == 0:
            return df

        # Normalize provider name for consistent column naming
        normalized_provider = self._normalize_provider_name(provider, key_config.key_name)

        # Create column name
        column_name = f"resource/tag:{normalized_provider}:{key_config.key_name}"

        # Use deterministic random service to allocate values
        return self.random_service.allocate_values_to_resources(
            df=df,
            values=key_config.values,
            context=f"tags_all:{key_config.key_name}",
            column_name=column_name
        )

    def build_tags_expression(self, key_config: 'KeyConfig', provider: str) -> pl.Expr:
        """
        Build Polars expression for tags allocation without creating intermediate DataFrames.

        Args:
            key_config: Key configuration with values to allocate
            provider: Provider name for column naming (will be normalized)

        Returns:
            Polars expression that can be used in with_columns()
        """
        # Normalize provider name for consistent column naming
        normalized_provider = self._normalize_provider_name(provider, key_config.key_name)

        # Create column name
        column_name = f"resource/tag:{normalized_provider}:{key_config.key_name}"

        # Build expression using the same logic as random service
        return self.random_service.build_value_allocation_expression(
            values=key_config.values,
            context=f"tags_all:{key_config.key_name}"
        ).alias(column_name)

    def _normalize_provider_name(self, provider: str, key_name: str = None) -> str:
        """
        Normalize provider name for column naming.

        Special case: Azure subscriptionName and resourceGroupName always use 'azure:' prefix.
        """
        provider_lower = provider.lower()

        # Special handling for Azure subscription and resource group tags
        if provider_lower in ['azure', 'microsoft azure', 'microsoft'] and key_name:
            key_lower = key_name.lower()
            if key_lower in ["subscriptionname", "resourcegroupname"]:
                return 'azure'

        if provider_lower in ['aws', 'amazon web services', 'amazon', 'aws marketplace']:
            return 'aws'
        elif provider_lower in ['azure', 'microsoft azure', 'microsoft']:
            return 'az'
        elif provider_lower in ['gcp', 'google cloud platform', 'google cloud', 'google']:
            return 'gcp_cz'
        elif provider_lower in ['oracle', 'oracle cloud', 'oci', 'oracle cloud infrastructure']:
            return 'orcl-cloud'
        elif provider_lower in ['anthropic']:
            return 'anthropic_cz'
        elif provider_lower in ['databricks']:
            return 'dbx_cz'
        else:
            # Remove spaces and special characters, convert to lowercase
            return provider_lower.replace(' ', '').replace('-', '').replace('_', '')