"""GCP-specific tag synchronization service for metadata stage."""

import polars as pl


class GcpTagsService:
    """
    Service for synchronizing GCP-specific CloudZero structural tags.

    Handles:
    - resource/tag:gcp_cz:resource_name sync when resource_id changes

    Does NOT handle:
    - resource/tag:gcp_cz:ancestry_display_name (set by generate stage, unchanged)
    - resource/tag:gcp_cz:project_name (handled by account service)
    - Native GCP labels like resource/tag:gcp:* (set by generate stage)
    """

    def sync_resource_name_with_resource_id(self, df: pl.DataFrame) -> pl.DataFrame:
        """
        Synchronize resource/tag:gcp_cz:resource_name with resource_id changes.

        GCP resource_name format: {resource_type}/{resource_id}
        - resource_type: Extracted from resource_id before '/' separator
        - resource_id: Full resource_id value

        Example:
        - resource_id: "instances/ml-platform-abc123"
        - resource_name: "instances/instances/ml-platform-abc123"

        Args:
            df: DataFrame with GCP resources (must have resource_id column)

        Returns:
            DataFrame with synchronized resource/tag:gcp_cz:resource_name column
        """
        if df.height == 0:
            return df

        # Only process if resource/tag:gcp_cz:resource_name column exists
        resource_name_col = "resource/tag:gcp_cz:resource_name"
        if resource_name_col not in df.columns:
            return df

        # Only process if resource_id column exists
        if "resource_id" not in df.columns:
            return df

        # Extract resource type from resource_id (part before '/')
        # Build new resource_name as {type}/{resource_id}
        return df.with_columns([
            self._build_resource_name_expression().alias(resource_name_col)
        ])

    def _build_resource_name_expression(self) -> pl.Expr:
        """
        Build Polars expression for resource_name sync.

        Extracts resource type from resource_id and reconstructs resource_name.
        Format: {resource_type}/{resource_id}

        Handles cases:
        - With separator: "instances/abc123" → "instances/instances/abc123"
        - Without separator: "simple-id" → "simple-id/simple-id" (fallback)

        Returns:
            Polars expression for resource_name column
        """
        # Split resource_id on '/' to get resource type
        segments = pl.col("resource_id").str.split("/")
        type_part = segments.list.get(0)

        # Check if resource_id contains '/' separator
        return (
            pl.when(pl.col("resource_id").str.contains("/"))
            .then(
                # Standard format: type/id → type/type/id
                pl.concat_str([
                    type_part,
                    pl.lit("/"),
                    pl.col("resource_id")
                ])
            )
            .otherwise(
                # No separator: id → id/id (fallback for simple IDs)
                pl.concat_str([
                    pl.col("resource_id"),
                    pl.lit("/"),
                    pl.col("resource_id")
                ])
            )
        )

    def build_resource_name_sync_expression(self) -> pl.Expr:
        """
        Build Polars expression for resource_name sync without DataFrame operations.

        Returns expression that can be used in with_columns() for efficient processing.

        Returns:
            Polars expression aliased as resource/tag:gcp_cz:resource_name
        """
        return self._build_resource_name_expression().alias("resource/tag:gcp_cz:resource_name")
