"""Cost isolation calculations for telemetry anomalies.

Single responsibility: Calculate target telemetry proportions that isolate
cost increases to the anomaly element during spike windows.

Key principle: Non-anomaly elements maintain baseline dollar costs while
anomaly element absorbs entire cost increase.
"""

from typing import Dict


class CostIsolationService:
    """Calculate target telemetry shares for cost isolation.

    Solves the proportional allocation problem: when shared resource cost
    increases 6x, how to prevent non-anomaly elements from seeing cost increases.

    Solution: Calculate target telemetry proportions such that non-anomaly
    elements maintain their baseline cost share relative to the new total.
    """

    def calculate_target_shares(
        self,
        baseline_shares: Dict[str, float],
        cost_multiplier: float,
        anomaly_element: str,
    ) -> Dict[str, float]:
        """Calculate target telemetry shares for cost isolation.

        Goal: Non-anomaly elements maintain baseline dollar costs.

        Formula:
            target_share_non_anomaly = baseline_share / cost_multiplier
            target_share_anomaly = 1 - sum(target_shares_non_anomaly)

        Args:
            baseline_shares: Element shares from Pass 3 (e.g., {"api-search": 0.6, ...})
            cost_multiplier: Cost increase factor (e.g., 6.0 for 6x increase)
            anomaly_element: Element with anomaly

        Returns:
            Target shares during anomaly (e.g., {"api-search": 0.933, ...})

        Example:
            >>> service = CostIsolationService()
            >>> baseline = {"api-search": 0.6, "api-auth": 0.4}
            >>> targets = service.calculate_target_shares(baseline, 6.0, "api-search")
            >>> targets
            {'api-auth': 0.0667, 'api-search': 0.9333}
        """
        self._validate_inputs(baseline_shares, cost_multiplier, anomaly_element)

        target_shares = {}

        # Calculate target shares for non-anomaly elements
        for element_id, baseline_share in baseline_shares.items():
            if element_id != anomaly_element:
                target_shares[element_id] = baseline_share / cost_multiplier

        # Anomaly element gets remainder
        target_shares[anomaly_element] = self._calculate_anomaly_remainder(
            target_shares
        )

        return target_shares

    def calculate_telemetry_multiplier(
        self, baseline_share: float, target_share: float
    ) -> float:
        """Calculate multiplier to achieve target share.

        Formula:
            telemetry_multiplier = target_share / baseline_share

        Args:
            baseline_share: Element's share before anomaly (e.g., 0.6)
            target_share: Element's target share during anomaly (e.g., 0.933)

        Returns:
            Multiplier to apply to element's telemetry (e.g., 9.33x)

        Example:
            >>> service = CostIsolationService()
            >>> multiplier = service.calculate_telemetry_multiplier(0.6, 0.9333)
            >>> round(multiplier, 2)
            15.56
        """
        if baseline_share <= 0:
            raise ValueError(f"baseline_share must be positive, got {baseline_share}")

        return target_share / baseline_share

    def _validate_inputs(
        self,
        baseline_shares: Dict[str, float],
        cost_multiplier: float,
        anomaly_element: str,
    ) -> None:
        """Validate calculation inputs."""
        if not baseline_shares:
            raise ValueError("baseline_shares cannot be empty")

        if anomaly_element not in baseline_shares:
            raise ValueError(
                f"anomaly_element '{anomaly_element}' not found in baseline_shares"
            )

        if cost_multiplier <= 1.0:
            raise ValueError(
                f"cost_multiplier must be > 1.0 (cost increase), got {cost_multiplier}"
            )

        # Verify shares sum to ~1.0
        total_share = sum(baseline_shares.values())
        if not (0.99 <= total_share <= 1.01):
            raise ValueError(
                f"baseline_shares must sum to ~1.0, got {total_share:.3f}"
            )

    def _calculate_anomaly_remainder(self, target_shares: Dict[str, float]) -> float:
        """Calculate anomaly element's share as remainder of 1.0."""
        non_anomaly_sum = sum(target_shares.values())
        return 1.0 - non_anomaly_sum
