"""
Validates connection suffix format and uniqueness.

Focused service for validating connection suffixes used in named connections.
Ensures suffix format compliance and prevents S3 path collisions.
"""

import re
from typing import Optional, Any


class ConnectionSuffixValidator:
    """Validates connection suffix format and prevents collisions."""

    def __init__(self, s3_client: Any):
        """
        Initialize validator with S3 client.

        Args:
            s3_client: S3 client for checking path existence
        """
        self.s3_client = s3_client

    def validate_suffix_format(self, suffix: str) -> None:
        """
        Validate suffix format.

        Rules:
        - Alphanumeric characters only
        - Hyphens allowed
        - No spaces or special characters

        Args:
            suffix: Connection suffix to validate

        Raises:
            ValueError: If format invalid

        Examples:
            Valid: 'Anomalies', 'Scenario-B', 'Q4-Spike'
            Invalid: 'Invalid Suffix' (space), 'Invalid_Suffix' (underscore)
        """
        if not re.match(r'^[A-Za-z0-9-]+$', suffix):
            raise ValueError(
                f"Invalid connection_suffix: '{suffix}'. "
                f"Must contain only alphanumeric characters and hyphens. "
                f"Examples: 'Anomalies', 'Scenario-B', 'Q4-Spike'"
            )

    def check_s3_path_collision(
        self,
        org: str,
        provider: str,
        suffix: Optional[str],
        allow_collision: bool = False
    ) -> None:
        """
        Check if S3 path already exists.

        Args:
            org: Organization name
            provider: Provider name (e.g., "AWS")
            suffix: Optional connection suffix
            allow_collision: If True, don't raise error (for recreate mode)

        Raises:
            ValueError: If path exists and allow_collision=False
        """
        # Build S3 folder path
        s3_folder = f"{provider}-{suffix}" if suffix else provider
        s3_prefix = f"piedpiper-custom-billing/{org}/{s3_folder}/"

        # Check if any objects exist with this prefix
        try:
            objects = self.s3_client.list_objects(s3_prefix)
            folder_exists = len(objects) > 0
        except Exception:
            # If listing fails, assume folder doesn't exist
            folder_exists = False

        if folder_exists and not allow_collision:
            bucket_name = self.s3_client.bucket_name
            raise ValueError(
                f"S3 folder already exists: s3://{bucket_name}/{s3_prefix}\n"
                f"Options:\n"
                f"  1. Use --recreate-connections to update existing\n"
                f"  2. Choose different connection_suffix\n"
                f"  3. Delete folder: aws s3 rm s3://{bucket_name}/{s3_prefix} --recursive"
            )
