"""Resource ID injection service for metadata stage."""

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


class ResourceIdInjectionService:
    """Service for injecting values into resource IDs (tags_only=false scenario)."""

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

    def inject_into_resource_ids(self, df: pl.DataFrame, key_config: KeyConfig) -> pl.DataFrame:
        """
        Prepend values to resource IDs.

        Assumes resource type prefix has already been dropped by preprocessing.
        Transforms: 12345-uuid → value-12345-uuid

        Args:
            df: DataFrame with resources
            key_config: Key configuration with values to inject

        Returns:
            DataFrame with modified resource_id column
        """
        if df.height == 0:
            return df

        if "resource_id" not in df.columns:
            raise ValueError("DataFrame must have 'resource_id' column for resource ID injection")

        # Use deterministic random service to select values
        df_with_values = self.random_service.allocate_values_to_resources(
            df=df,
            values=key_config.values,
            context=f"resource_id_injection:{key_config.key_name}",
            column_name=f"_injection_value_{key_config.key_name}"
        )

        # Inject values into resource IDs
        injection_column = f"_injection_value_{key_config.key_name}"

        result = df_with_values.with_columns([
            self._inject_value_expression(injection_column).alias("resource_id")
        ]).drop(injection_column)

        return result

    def _inject_value_expression(self, value_column: str) -> pl.Expr:
        """
        Create Polars expression for prepending value to resource ID.

        Assumes resource type prefix has already been dropped by preprocessing.
        Prepends value to cleaned resource ID:
        - 12345 → value-12345
        - 67890-suffix → value-67890-suffix

        Args:
            value_column: Name of column containing value to inject

        Returns:
            Polars expression for modified resource_id
        """
        return (
            pl.concat_str([
                pl.col(value_column),
                pl.lit("-"),
                pl.col("resource_id")
            ])
        )