"""
Connection ID resolution for ad-hoc and generated uploads.

Separates connection resolution logic from upload orchestration following
Single Responsibility Principle.
"""

from typing import List, Dict, Any
from ..models import Organization


class ConnectionResolver:
    """
    Resolves connection IDs for uploads based on upload type and configuration.

    Single Responsibility: Determine which connection IDs to use for a provider.
    """

    def resolve_for_adhoc(
        self,
        org: Organization,
        provider: str
    ) -> List[str]:
        """
        Resolve connection IDs for ad-hoc upload.

        Ad-hoc uploads REQUIRE explicit connection IDs in config.
        Auto-creation is not supported because:
        - External data with unknown S3 structure
        - Connections must be configured manually in CloudZero UI

        Args:
            org: Organization configuration
            provider: Provider name (AWS, Azure, GCP, CNS, etc.)

        Returns:
            List of connection IDs

        Raises:
            ValueError: If no connections configured for provider
        """
        if not org.connections or provider not in org.connections:
            raise ValueError(
                f"Ad-hoc upload requires explicit connection IDs for provider '{provider}'.\n\n"
                f"To fix this:\n"
                f"1. Create a billing connection in CloudZero UI (Settings > Connections)\n"
                f"2. Add the connection ID to your config:\n\n"
                f"  organizations:\n"
                f"    {org.name}:\n"
                f"      connections:\n"
                f"        {provider}:\n"
                f"          - \"your-connection-id-here\"\n\n"
                f"Find connection IDs in CloudZero UI under Settings > Connections."
            )

        connection_ids = org.connections[provider]

        if not connection_ids:
            raise ValueError(
                f"Empty connection list for provider '{provider}' in organization '{org.name}'. "
                f"Please specify at least one connection ID."
            )

        return connection_ids

    def resolve_for_generated(
        self,
        org: Organization,
        provider: str,
        connection_manager,
        payload_count: int,
        s3_config: Dict[str, Any]
    ) -> List[str]:
        """
        Resolve connection IDs for generated dataset upload.

        Generated uploads support both:
        - Explicit connection IDs (if provided in config)
        - Auto-created connections (if not provided)

        Args:
            org: Organization configuration
            provider: Provider name
            connection_manager: Connection manager for auto-creation
            payload_count: Number of payloads to upload
            s3_config: S3 configuration dict

        Returns:
            List of connection IDs
        """
        # Use explicit connections if provided
        if org.connections and provider in org.connections:
            return org.connections[provider]

        # Auto-create connections for generated uploads
        connections_needed = max(1, (payload_count + 15) // 16)

        return connection_manager.ensure_connections(
            provider=provider,
            count=connections_needed,
            s3_bucket_name=s3_config["bucket"],
            s3_root_folder=s3_config["root_folder"],
            s3_org_folder=org.name,
            role_arn=s3_config["role_arn"],
            external_id=s3_config["external_id"]
        )
