"""
Connection management utilities for CloudZero billing connections.

Provides helper functions for connection naming, creation, and validation
following patterns from cz-demo-tools.
"""

import os
from typing import Dict, List, Optional
from .client import CloudZeroConnection


def generate_provider_connection_name(provider: str, connection_suffix: Optional[str] = None) -> str:
    """
    Generate a provider connection name with timestamp in the format: aws_bc_0001_20250910-1320
    or with suffix: aws_suffix_bc_0001_20250910-1320

    Args:
        provider: Provider name (AWS, Azure, GCP, AWS Marketplace, etc.)
        connection_suffix: Optional suffix for custom naming

    Returns:
        Generated connection name with timestamp (format: provider_bc_0001_YYYYMMDD-HHMM or provider_suffix_bc_0001_YYYYMMDD-HHMM)
    """
    from datetime import datetime

    # Convert to lowercase and replace spaces with underscores
    clean_provider = provider.lower().replace(' ', '_')

    # Add human readable timestamp (down to the minute)
    timestamp = datetime.now().strftime('%Y%m%d-%H%M')

    # Format with suffix if provided: provider_suffix_bc_0001_YYYYMMDD-HHMM
    # Format without suffix: provider_bc_0001_YYYYMMDD-HHMM
    if connection_suffix:
        # Normalize suffix: replace hyphens with underscores
        suffix_normalized = connection_suffix.lower().replace("-", "_")
        return f"{clean_provider}_{suffix_normalized}_bc_0001_{timestamp}"
    return f"{clean_provider}_bc_0001_{timestamp}"


def get_provider_display_name(provider: str) -> str:
    """
    Get the correct display name for a provider.
    
    Args:
        provider: Provider name (AWS, Azure, GCP)
        
    Returns:
        Correct display name for CloudZero API
    """
    provider_mapping = {
        "AWS": "AWS.",  # Must have period for data quality
        "Azure": "Azure",
        "GCP": "GCP"
    }
    
    return provider_mapping.get(provider.upper(), provider)


def create_cloudzero_connection(
    provider: str,
    s3_bucket_name: str,
    s3_root_folder: str,
    s3_org_folder: str,
    role_arn: str,
    external_id: str,
    connection_suffix: Optional[str] = None
) -> CloudZeroConnection:
    """
    Create a CloudZeroConnection object for a provider.

    Args:
        provider: Provider name (AWS, Azure, GCP)
        s3_bucket_name: S3 bucket name
        s3_root_folder: S3 root folder
        s3_org_folder: S3 organization folder
        role_arn: AWS IAM role ARN
        external_id: AWS IAM external ID
        connection_suffix: Optional suffix for custom connection naming

    Returns:
        CloudZeroConnection object
    """
    connection_name = generate_provider_connection_name(provider, connection_suffix)
    display_name = get_provider_display_name(provider)
    s3_bucket_path = f"{s3_root_folder}/{s3_org_folder}/{provider}"
    
    return CloudZeroConnection(
        name=connection_name,
        cloud_provider=display_name,
        s3_bucket_name=s3_bucket_name,
        s3_bucket_path=s3_bucket_path,
        role_arn=role_arn,
        external_id=external_id,
        is_enabled=True
    )


def validate_cloudzero_config() -> Dict[str, str]:
    """
    Validate CloudZero configuration using SecretsResolver.

    Returns:
        Dictionary with validated configuration

    Raises:
        ValueError: If required configuration is missing
    """
    from ..services.secrets_resolver import SecretsResolver

    # Try to get connection config using SecretsResolver
    secrets_resolver = SecretsResolver()

    # Get connection config (IAM role and external ID)
    conn_config = secrets_resolver.get_connection_config()

    # Get generic API key if available (for backward compatibility)
    api_key = os.environ.get("CZ_ORG_API_KEY")

    result = {
        "AWS_IAM_ROLE_ARN": conn_config["aws_iam_role_arn"],
        "AWS_IAM_EXTERNAL_ID": conn_config["aws_iam_external_id"]
    }

    if api_key:
        result["CZ_ORG_API_KEY"] = api_key

    return result


def get_org_api_key(org_name: str) -> str:
    """
    Get organization-specific API key.

    Resolution order:
    1. Environment variables (CLI and ECS task definition)
    2. AWS Secrets Manager (ECS dynamic retrieval)

    Args:
        org_name: Organization name

    Returns:
        API key for the organization

    Raises:
        ValueError: If API key not found
    """
    from ..services.secrets_resolver import SecretsResolver

    environment = os.getenv("CZBILLGEN_ENV", "dev")
    region = os.getenv("AWS_REGION", "us-east-1")

    resolver = SecretsResolver(environment=environment, region=region)
    return resolver.get_org_api_key(org_name)


class ConnectionManager:
    """
    High-level connection management for czbillgen upload operations.
    
    Provides simplified interface for connection validation and auto-creation
    during upload operations.
    """
    
    def __init__(self, api_key: str):
        """
        Initialize connection manager.
        
        Args:
            api_key: CloudZero API key
        """
        from .client import CloudZeroAPI
        self.api = CloudZeroAPI(api_key)
    
    def validate_connections_exist(self, providers: List[str]) -> Dict[str, bool]:
        """
        Validate that connections exist for all specified providers.

        Each provider validates its own connection.

        Args:
            providers: List of provider names

        Returns:
            Dictionary mapping provider names to existence status
        """
        from src.upload.services.provider_mapping_service import ProviderMappingService

        provider_mapping = ProviderMappingService()
        results = {}

        for provider in providers:
            # Map to connection provider (each provider uses its own connection)
            connection_provider = provider_mapping.get_connection_provider(provider)
            connection = self.api.find_enabled_bucket_connection(connection_provider)
            results[provider] = connection is not None

        return results
    
    def ensure_all_connections(self, providers: List[str], s3_config: Dict[str, str], connection_suffix: Optional[str] = None) -> Dict[str, Dict]:
        """
        Ensure all required connections exist, creating them if necessary.

        Each provider gets its own connection to preserve column schemas.

        Args:
            providers: List of provider names
            s3_config: S3 configuration with bucket details
            connection_suffix: Optional suffix for custom connection naming

        Returns:
            Dictionary mapping provider names to connection details
        """
        from src.upload.services.provider_mapping_service import ProviderMappingService
        from ..services.secrets_resolver import SecretsResolver

        provider_mapping = ProviderMappingService()

        # Get AWS IAM configuration using SecretsResolver
        secrets_resolver = SecretsResolver()
        conn_config = secrets_resolver.get_connection_config()

        aws_iam_role = conn_config["aws_iam_role_arn"]
        aws_iam_external_id = conn_config["aws_iam_external_id"]

        # Map providers to connection providers (each provider uses its own connection)
        connection_providers = []
        for provider in providers:
            connection_provider = provider_mapping.get_connection_provider(provider)
            connection_providers.append(connection_provider)

        # Ensure connections for all providers
        return self.api.ensure_provider_bucket_connections(
            providers=connection_providers,
            s3_bucket_name=s3_config["bucket_name"],
            s3_root_folder=s3_config["root_folder"],
            s3_org_folder=s3_config["org_folder"],
            role_arn=aws_iam_role,
            external_id=aws_iam_external_id,
            connection_suffix=connection_suffix
        )