"""
CloudZero connection management for upload operations.

Handles validation of CloudZero billing connections and API token management
for multi-organization uploads.
"""

import os
from typing import Dict, List, Optional
from dataclasses import dataclass

from ...services.environment_service import EnvironmentService
from ...log_context import get_logger


@dataclass
class ConnectionInfo:
    """Information about a CloudZero billing connection."""
    connection_id: str
    provider: str
    organization: str
    is_valid: bool = True
    error_message: Optional[str] = None


class ConnectionManager:
    """
    Manages CloudZero billing connections for upload operations.
    
    Handles validation of connection IDs and API token management
    for multi-organization uploads.
    """
    
    def __init__(self):
        """Initialize connection manager."""
        self.logger = get_logger(__name__)
        self.env_service = EnvironmentService()
    
    def validate_organization_connections(
        self, 
        org_name: str, 
        api_token_env: str,
        providers: Dict[str, List[str]]
    ) -> Dict[str, List[ConnectionInfo]]:
        """
        Validate connections for an organization.
        
        Args:
            org_name: Organization name
            api_token_env: Environment variable name for API token
            providers: Dict of provider -> list of connection IDs
            
        Returns:
            Dict of provider -> list of ConnectionInfo objects
        """
        results = {}
        
        # Validate API token exists
        try:
            api_token = self.env_service.require(api_token_env)
            if not api_token:
                raise ValueError(f"API token not found: {api_token_env}")
        except Exception as e:
            self.logger.error(f"API token validation failed for {org_name}: {e}")
            # Return empty results if no API token
            return {provider: [] for provider in providers.keys()}
        
        # Validate each provider's connections
        for provider, connection_ids in providers.items():
            provider_connections = []
            
            for connection_id in connection_ids:
                if not connection_id:
                    # Skip empty connection IDs
                    continue
                
                connection_info = ConnectionInfo(
                    connection_id=connection_id,
                    provider=provider,
                    organization=org_name
                )
                
                # Basic validation (format checking)
                if not self._validate_connection_format(connection_id):
                    connection_info.is_valid = False
                    connection_info.error_message = "Invalid connection ID format"
                    self.logger.warning(f"Invalid connection ID format: {connection_id}")
                
                provider_connections.append(connection_info)
            
            results[provider] = provider_connections
        
        return results
    
    def get_valid_connections(
        self, 
        org_name: str, 
        api_token_env: str,
        providers: Dict[str, List[str]]
    ) -> Dict[str, List[str]]:
        """
        Get only valid connection IDs for an organization.
        
        Args:
            org_name: Organization name
            api_token_env: Environment variable name for API token
            providers: Dict of provider -> list of connection IDs
            
        Returns:
            Dict of provider -> list of valid connection IDs
        """
        connection_results = self.validate_organization_connections(
            org_name, api_token_env, providers
        )
        
        valid_connections = {}
        for provider, connections in connection_results.items():
            valid_ids = [
                conn.connection_id for conn in connections 
                if conn.is_valid
            ]
            valid_connections[provider] = valid_ids
        
        return valid_connections
    
    def validate_api_token(self, api_token_env: str) -> bool:
        """
        Validate that API token is available and properly formatted.
        
        Args:
            api_token_env: Environment variable name for API token
            
        Returns:
            True if API token is valid, False otherwise
        """
        try:
            api_token = self.env_service.get(api_token_env)
            
            if not api_token:
                return False
            
            # Check for placeholder values
            if api_token in ["your-cloudzero-api-token-here", "your-token-here"]:
                return False
            
            # Basic format check (CloudZero API tokens are typically longer)
            if len(api_token) < 20:
                return False
            
            return True
            
        except Exception:
            return False
    
    def _validate_connection_format(self, connection_id: str) -> bool:
        """
        Validate connection ID format.
        
        Args:
            connection_id: Connection ID to validate
            
        Returns:
            True if format is valid, False otherwise
        """
        if not connection_id:
            return False
        
        # Basic format checks
        if len(connection_id) < 5:
            return False
        
        # Check for obvious placeholder values
        if connection_id in [
            "your-connection-id-here",
            "your-aws-connection-id-here",
            "your-gcp-connection-id-here",
            "your-azure-connection-id-here"
        ]:
            return False
        
        return True
    
    def get_connection_summary(
        self, 
        org_name: str, 
        api_token_env: str,
        providers: Dict[str, List[str]]
    ) -> Dict[str, any]:
        """
        Get summary of connection validation results.
        
        Args:
            org_name: Organization name
            api_token_env: Environment variable name for API token
            providers: Dict of provider -> list of connection IDs
            
        Returns:
            Summary dictionary with validation results
        """
        summary = {
            "organization": org_name,
            "api_token_valid": self.validate_api_token(api_token_env),
            "providers": {},
            "total_connections": 0,
            "valid_connections": 0,
            "invalid_connections": 0
        }
        
        connection_results = self.validate_organization_connections(
            org_name, api_token_env, providers
        )
        
        for provider, connections in connection_results.items():
            valid_count = sum(1 for conn in connections if conn.is_valid)
            invalid_count = len(connections) - valid_count
            
            summary["providers"][provider] = {
                "total": len(connections),
                "valid": valid_count,
                "invalid": invalid_count,
                "connections": [
                    {
                        "id": conn.connection_id,
                        "valid": conn.is_valid,
                        "error": conn.error_message
                    } for conn in connections
                ]
            }
            
            summary["total_connections"] += len(connections)
            summary["valid_connections"] += valid_count
            summary["invalid_connections"] += invalid_count
        
        return summary