"""
Simplified variance processing using Polars vectorized operations.

Single focused function following KISS principles and CloudZero coding standards.
"""

import hashlib
import numpy as np
import polars as pl


def apply_variance(df: pl.DataFrame, config: dict, resource_id: str) -> pl.DataFrame:
    """
    Apply variance to cost column using Polars vectorized operations.
    
    Creates obvious visual differences for compelling CloudZero charts.
    Uses deterministic randomness for reproducible results.
    
    Args:
        df: DataFrame with cost column
        config: Variance configuration (daily_variance_pct, hourly_variance_pct)
        resource_id: Unique resource identifier for deterministic seeding
        
    Returns:
        DataFrame with variance applied to cost column
    """
    if len(df) == 0:
        return df
    
    # Parse configuration - use daily variance as default
    variance_pct = config.get("daily_variance_pct", 50)
    
    # Generate deterministic seed for reproducible results
    seed = _generate_deterministic_seed(resource_id, "variance")
    np.random.seed(seed)
    
    # Generate random multipliers using vectorized NumPy operations
    n_rows = len(df)
    min_multiplier = 1.0 - (variance_pct / 100.0)
    max_multiplier = 1.0 + (variance_pct / 100.0)
    
    # Create array of random multipliers
    multipliers = np.random.uniform(min_multiplier, max_multiplier, n_rows)
    
    # Apply variance using Polars vectorized operations
    result_df = df.with_columns([
        (pl.col("hourly_cost") * pl.Series("multipliers", multipliers)).alias("hourly_cost")
    ])
    
    return result_df


def _generate_deterministic_seed(resource_id: str, context: str) -> int:
    """Generate deterministic seed for reproducible randomness."""
    combined = f"{context}_{resource_id}"
    hash_value = hashlib.md5(combined.encode()).hexdigest()
    return int(hash_value[:8], 16) % (2**32)