"""Service for Azure resource ID segment modifications."""

import polars as pl
from typing import Dict, Optional
import re


class AzureResourceIdService:
    """Service for Azure resource ID segment modifications."""

    def __init__(self):
        """Initialize service (no dependencies needed)."""
        pass

    def update_subscription_in_resource_id(
        self,
        df: pl.DataFrame,
        account_column: str = "cloud_account"
    ) -> pl.DataFrame:
        """
        Update subscription segment in Azure resource IDs based on account column.

        Args:
            df: DataFrame with resources containing resource_id and account columns
            account_column: Column name containing account values with subscription IDs

        Returns:
            DataFrame with updated resource_id column

        Raises:
            ValueError: If required columns missing or account format invalid
        """
        if df.height == 0:
            return df

        required_columns = ["resource_id", account_column]
        missing_columns = [col for col in required_columns if col not in df.columns]
        if missing_columns:
            raise ValueError(f"Missing required columns: {missing_columns}")

        # Extract subscription IDs and update resource IDs
        return df.with_columns([
            self._build_subscription_update_expression(account_column).alias("resource_id")
        ])

    def update_resource_group_in_resource_id(
        self,
        df: pl.DataFrame,
        resource_group_column: str
    ) -> pl.DataFrame:
        """
        Update resource group segment in Azure resource IDs.

        Args:
            df: DataFrame with resources containing resource_id and resource group columns
            resource_group_column: Column name containing resource group names

        Returns:
            DataFrame with updated resource_id column

        Raises:
            ValueError: If required columns missing
        """
        if df.height == 0:
            return df

        required_columns = ["resource_id", resource_group_column]
        missing_columns = [col for col in required_columns if col not in df.columns]
        if missing_columns:
            raise ValueError(f"Missing required columns: {missing_columns}")

        # Update resource group in resource IDs
        return df.with_columns([
            self._build_resource_group_update_expression(resource_group_column).alias("resource_id")
        ])

    def _extract_subscription_id(self, account_value: str) -> str:
        """
        Extract subscription ID from account value.

        Args:
            account_value: Account value in format "name|sub-id"

        Returns:
            Subscription ID (e.g., "sub-01AAXgJtYKjjBHpbo9ui7Y9A")

        Raises:
            ValueError: If account format is invalid
        """
        if "|" not in account_value:
            raise ValueError(f"Invalid account format: {account_value}. Expected format: 'name|sub-id'")

        parts = account_value.split("|")
        if len(parts) != 2 or not parts[1].startswith("sub-"):
            raise ValueError(f"Invalid subscription ID in account: {account_value}")

        return parts[1]

    def _parse_azure_resource_id(self, resource_id: str) -> Dict[str, str]:
        """
        Parse Azure resource ID into components.

        Args:
            resource_id: Azure resource ID

        Returns:
            Dictionary with parsed components

        Raises:
            ValueError: If resource ID format is invalid
        """
        if not resource_id.startswith("/subscriptions/"):
            raise ValueError(f"Invalid Azure resource ID format: {resource_id}")

        # Azure resource ID pattern: /subscriptions/{sub}/resourceGroups/{rg}/providers/{provider}/{type}/{name}
        pattern = r"^/subscriptions/([^/]+)/resourceGroups/([^/]+)/(.+)$"
        match = re.match(pattern, resource_id)

        if not match:
            raise ValueError(f"Invalid Azure resource ID structure: {resource_id}")

        subscription_id, resource_group, remainder = match.groups()

        return {
            "subscription_id": subscription_id,
            "resource_group": resource_group,
            "remainder": remainder
        }

    def _build_azure_resource_id(self, components: Dict[str, str]) -> str:
        """
        Rebuild Azure resource ID from components.

        Args:
            components: Dictionary with subscription_id, resource_group, and remainder

        Returns:
            Complete Azure resource ID
        """
        return f"/subscriptions/{components['subscription_id']}/resourceGroups/{components['resource_group']}/{components['remainder']}"

    def _build_subscription_update_expression(self, account_column: str) -> pl.Expr:
        """
        Build Polars expression to update subscription in resource IDs.

        Args:
            account_column: Column name containing account values

        Returns:
            Polars expression for updated resource_id
        """
        # Extract subscription ID from account column (after | delimiter)
        subscription_expr = pl.col(account_column).str.split("|").list.get(1)

        # Replace subscription segment in resource ID using regex
        return pl.col("resource_id").str.replace_all(
            r"/subscriptions/[^/]+/",
            pl.concat_str([
                pl.lit("/subscriptions/"),
                subscription_expr,
                pl.lit("/")
            ])
        )

    def _build_resource_group_update_expression(self, resource_group_column: str) -> pl.Expr:
        """
        Build Polars expression to update resource group in resource IDs.

        Args:
            resource_group_column: Column name containing resource group names

        Returns:
            Polars expression for updated resource_id
        """

        # Replace resource group segment in resource ID using regex
        return pl.col("resource_id").str.replace_all(
            r"/resourceGroups/[^/]+/",
            pl.concat_str([
                pl.lit("/resourceGroups/"),
                pl.col(resource_group_column),
                pl.lit("/")
            ])
        )