"""Path resolution service for config upload/download."""


class ConfigPathResolver:
    """Converts between local paths and S3 keys.

    Handles all path normalization and conversion logic in one place,
    ensuring consistent path handling across upload and download operations.
    """

    def __init__(self, base_prefix: str = "czbillgen/configs/"):
        """Initialize path resolver with S3 base prefix.

        Args:
            base_prefix: S3 key prefix for all configs (default: "czbillgen/configs/")
        """
        self.base_prefix = base_prefix

    def local_to_s3_key(self, local_path: str, ensure_trailing_slash: bool = False) -> str:
        """Convert local path to S3 key.

        Args:
            local_path: Local file or directory path (e.g., "generate/production/aws.yaml")
            ensure_trailing_slash: If True, ensure path ends with / (for directories)

        Returns:
            S3 key with base prefix (e.g., "czbillgen/configs/generate/production/aws.yaml")
        """
        # Normalize path: remove leading ./
        normalized = local_path.lstrip("./")

        # Remove trailing slash, then optionally add it back
        normalized = normalized.rstrip("/")
        if ensure_trailing_slash:
            normalized = normalized + "/"

        # Add base prefix if not present
        if not normalized.startswith(self.base_prefix):
            return f"{self.base_prefix}{normalized}"
        return normalized

    def s3_to_local_path(self, s3_key: str) -> str:
        """Convert S3 key to local path.

        Args:
            s3_key: S3 object key (e.g., "czbillgen/configs/generate/production/aws.yaml")

        Returns:
            Local file path (e.g., "./czbg-configs/generate/production/aws.yaml")
        """
        # Remove base prefix and leading slash
        path = s3_key.replace(self.base_prefix, "", 1).lstrip("/")

        # Add local base directory
        return f"./czbg-configs/{path}"

    def list_prefix_from_path(self, path: str) -> str:
        """Normalize path for S3 list operations.

        Args:
            path: Path to list (e.g., "generate/production")

        Returns:
            S3 prefix for listing (e.g., "czbillgen/configs/generate/production/")
        """
        return self.local_to_s3_key(path, ensure_trailing_slash=True)
