"""
Connection lifecycle manager for CloudZero connections.

Manages connection creation, deletion, and recreation operations
independently from data lifecycle.
"""

from typing import Optional
from dataclasses import dataclass


@dataclass
class ConnectionConfig:
    """Configuration for connection creation."""
    org: str
    provider: str
    suffix: Optional[str] = None
    s3_bucket: str = ""
    s3_root_folder: str = "piedpiper-custom-billing"
    s3_org_folder: str = ""
    role_arn: str = ""
    external_id: str = ""


class ConnectionLifecycleManager:
    """
    Manages CloudZero connection lifecycle operations.

    Single Responsibility: CloudZero connection CRUD operations only.
    Does NOT manage S3 data lifecycle.
    """

    def __init__(self, api_client):
        """
        Initialize connection lifecycle manager.

        Args:
            api_client: CloudZero API client for connection operations
        """
        self.api_client = api_client

    def delete_connection(
        self,
        org: str,
        provider: str,
        suffix: Optional[str] = None
    ) -> None:
        """
        Delete CloudZero billing connection.

        Args:
            org: Organization name
            provider: Provider name (AWS, Azure, GCP)
            suffix: Optional connection suffix

        Raises:
            RuntimeError: If connection deletion fails
        """
        # Find existing connection
        connection = self.api_client.find_enabled_bucket_connection(provider)

        if not connection:
            print(f"   ⚠️  No connection found for {provider}, skipping deletion")
            return

        # Delete connection
        connection_id = connection.get("id")
        try:
            self.api_client.delete_billing_connection(connection_id)
            print(f"   ✅ Deleted connection: {provider}")
        except Exception as e:
            raise RuntimeError(f"Failed to delete connection {connection_id}: {str(e)}")

    def create_connection(
        self,
        config: ConnectionConfig
    ) -> str:
        """
        Create new CloudZero billing connection.

        Args:
            config: Connection configuration

        Returns:
            Connection ID of created connection

        Raises:
            RuntimeError: If connection creation fails
        """
        from ..api.anycost_connection_manager import AnyCostConnectionManager

        # Use existing connection manager for creation
        manager = AnyCostConnectionManager(self.api_client)

        try:
            connection_ids = manager.ensure_connections(
                provider=config.provider,
                count=1,
                s3_bucket_name=config.s3_bucket,
                s3_root_folder=config.s3_root_folder,
                s3_org_folder=config.s3_org_folder,
                role_arn=config.role_arn,
                external_id=config.external_id,
                connection_suffix=config.suffix
            )

            print(f"   ✅ Created connection: {config.provider}")
            return connection_ids[0]

        except Exception as e:
            raise RuntimeError(f"Failed to create connection: {str(e)}")

    def recreate_connection(
        self,
        config: ConnectionConfig
    ) -> str:
        """
        Recreate CloudZero billing connection (delete + create).

        Args:
            config: Connection configuration

        Returns:
            Connection ID of new connection
        """
        print(f"   🔄 Recreating connection: {config.provider}")

        # Delete existing connection
        self.delete_connection(config.org, config.provider, config.suffix)

        # Create new connection
        return self.create_connection(config)
