"""
Telemetry Profile Converters

Convert unified profile patterns to telemetry configuration objects.
"""

import random
from typing import Any, Dict, Optional

# Import telemetry configuration classes
from ...telemetry.patterns import (
    AnomalyConfig,
    SeasonalityConfig,
    TrendConfig,
)
from ..patterns.anomaly import AnomalyType, get_anomaly_pattern
from ..patterns.distribution import DistributionStrategy, get_distribution_pattern
from ..patterns.growth import GrowthType, get_growth_pattern
from ..patterns.seasonality import SeasonalityType, get_seasonality_pattern


def convert_growth_profile_for_telemetry(profile_name: str) -> Optional[TrendConfig]:
    """Convert unified growth profile to telemetry TrendConfig."""
    if profile_name == "stable":
        return None

    pattern = get_growth_pattern(profile_name)

    if pattern.growth_type == GrowthType.NONE:
        return None
    elif pattern.growth_type == GrowthType.LINEAR:
        return TrendConfig(
            type="linear", growth_rate=pattern.growth_rate, cap=pattern.cap
        )
    elif pattern.growth_type == GrowthType.EXPONENTIAL:
        return TrendConfig(
            type="exponential", growth_rate=pattern.growth_rate, cap=pattern.cap
        )
    elif pattern.growth_type == GrowthType.LOGISTIC:
        return TrendConfig(
            type="logistic", growth_rate=pattern.growth_rate, cap=pattern.cap or 3.0
        )
    elif pattern.growth_type == GrowthType.DECLINE:
        return TrendConfig(
            type="linear",
            growth_rate=pattern.growth_rate,  # Negative growth rate
            cap=pattern.cap,
        )
    else:
        raise ValueError(f"Unsupported growth type: {pattern.growth_type}")


def convert_seasonality_profile_for_telemetry(
    profile_name: str,
) -> Optional[SeasonalityConfig]:
    """Convert unified seasonality profile to telemetry SeasonalityConfig."""
    if profile_name == "none":
        return None

    pattern = get_seasonality_pattern(profile_name)

    if pattern.seasonality_type == SeasonalityType.NONE:
        return None
    elif pattern.seasonality_type == SeasonalityType.WEEKLY:
        return SeasonalityConfig(
            pattern="weekly", amplitude=pattern.amplitude, phase=pattern.phase
        )
    elif pattern.seasonality_type == SeasonalityType.MONTHLY:
        return SeasonalityConfig(
            pattern="monthly", amplitude=pattern.amplitude, phase=pattern.phase
        )
    elif pattern.seasonality_type == SeasonalityType.YEARLY:
        return SeasonalityConfig(
            pattern="yearly", amplitude=pattern.amplitude, phase=pattern.phase
        )
    else:
        # Map quarterly to yearly for telemetry system
        return SeasonalityConfig(
            pattern="yearly",
            amplitude=pattern.amplitude * 0.5,  # Reduce amplitude for yearly mapping
            phase=pattern.phase,
        )


def convert_anomaly_profile_for_telemetry(
    profile_name: str, seed: int = 42
) -> Optional[AnomalyConfig]:
    """Convert unified anomaly profile to telemetry AnomalyConfig."""
    if profile_name == "none":
        return None

    pattern = get_anomaly_pattern(profile_name)

    if pattern.anomaly_type == AnomalyType.NONE:
        return None
    else:
        return AnomalyConfig(
            frequency=pattern.frequency,
            magnitude=pattern.magnitude,
            duration=pattern.duration,
            seed=seed,
        )


def convert_distribution_profile_for_telemetry(
    profile_name: str, element_count: int, seed: int = 42
) -> Dict[str, Any]:
    """Convert unified distribution profile to telemetry distribution configuration."""
    pattern = get_distribution_pattern(profile_name)

    if pattern.strategy == DistributionStrategy.BALANCED:
        # Perfectly balanced
        weights = [1.0 / element_count] * element_count
        return {"strategy": "weighted", "weights": weights, "seed": seed}
    elif pattern.strategy == DistributionStrategy.WEIGHTED:
        # Light to moderate skew with weighted distribution
        random.seed(seed)
        skew = pattern.skew_factor

        # Create skewed weights
        weights = []
        for i in range(element_count):
            # Higher indices get lower weights based on skew factor
            weight = (1 - skew) + skew * (element_count - i) / element_count
            weights.append(weight)

        # Normalize weights
        total_weight = sum(weights)
        weights = [w / total_weight for w in weights]

        return {"strategy": "weighted", "weights": weights, "seed": seed}
    elif pattern.strategy in [
        DistributionStrategy.PARETO,
        DistributionStrategy.CONCENTRATED,
    ]:
        # Pareto distribution
        return {
            "strategy": "pareto",
            "pareto_factor": pattern.skew_factor,
            "seed": seed,
        }
    else:
        raise ValueError(f"Unknown distribution strategy: {pattern.strategy}")


def convert_usage_intensity_for_telemetry(profile_name: str) -> float:
    """Convert growth pattern base variance to telemetry usage intensity."""
    pattern = get_growth_pattern(profile_name)
    return pattern.base_variance


def apply_unified_profiles_to_telemetry_config(
    config_dict: Dict[str, Any],
) -> Dict[str, Any]:
    """Apply all unified profiles to convert simplified config to full telemetry config."""
    result = config_dict.copy()

    # Convert scale profile (unchanged - telemetry specific)
    if "scale_profile" in result:
        # This would need telemetry-specific scale conversion
        pass

    # Convert variance from growth pattern base variance
    if "growth_profile" in result:
        variance = convert_usage_intensity_for_telemetry(result["growth_profile"])
        result["variance_factor"] = variance

    # Convert seasonality profile
    if "seasonality_profile" in result:
        seasonality = convert_seasonality_profile_for_telemetry(
            result.pop("seasonality_profile")
        )
        if seasonality:
            result["seasonality"] = seasonality

    # Convert growth profile
    if "growth_profile" in result:
        trend = convert_growth_profile_for_telemetry(result.pop("growth_profile"))
        if trend:
            result["trend"] = trend

    # Convert anomaly profile
    if "anomaly_profile" in result:
        seed = result.get("seed", 42)
        anomaly = convert_anomaly_profile_for_telemetry(
            result.pop("anomaly_profile"), seed
        )
        if anomaly:
            result["anomaly"] = anomaly

    # Convert distribution profile (requires element count)
    if "distribution_profile" in result and "elements" in result:
        seed = result.get("seed", 42)
        element_count = (
            len(result["elements"]["list"])
            if isinstance(result["elements"], dict)
            else len(result["elements"])
        )

        distribution_config = convert_distribution_profile_for_telemetry(
            result.pop("distribution_profile"), element_count, seed
        )

        # Apply to elements.distribution
        if "elements" in result:
            if isinstance(result["elements"], dict):
                if "distribution" not in result["elements"]:
                    result["elements"]["distribution"] = {}
                result["elements"]["distribution"].update(distribution_config)
            else:
                # Handle list case - convert to dict format
                elements_list = result["elements"]
                result["elements"] = {
                    "type": "provided",
                    "list": elements_list,
                    "distribution": distribution_config,
                }

    return result
