"""S3 operations for config upload/download."""

from typing import List, Dict, Any


class ConfigS3Operations:
    """Handles all S3 operations for config files.

    Wraps S3DataService with focused methods for config upload/download.
    Single responsibility: S3 operations for config files only.
    """

    def __init__(self, s3_service):
        """Initialize with S3DataService dependency.

        Args:
            s3_service: Instance of S3DataService for S3 operations
        """
        self.s3_service = s3_service

    def upload_file(self, s3_key: str, content: bytes) -> None:
        """Upload file content to S3.

        Args:
            s3_key: S3 key (path) to upload to
            content: File content as bytes

        Raises:
            Exception: If S3 upload fails
        """
        # Write content to temp file and upload
        import tempfile
        from pathlib import Path

        with tempfile.NamedTemporaryFile(delete=False, mode='wb') as tmp_file:
            tmp_file.write(content)
            tmp_path = tmp_file.name

        try:
            self.s3_service.upload_file(tmp_path, s3_key)
        finally:
            Path(tmp_path).unlink()

    def download_file(self, s3_key: str) -> bytes:
        """Download file content from S3.

        Args:
            s3_key: S3 key (path) to download from

        Returns:
            File content as bytes

        Raises:
            Exception: If S3 download fails
        """
        # Use s3_client directly to get file content
        response = self.s3_service.s3_client.get_object(
            Bucket=self.s3_service.bucket,
            Key=s3_key
        )
        return response['Body'].read()

    def list_files(self, prefix: str) -> List[Dict[str, Any]]:
        """List all files under S3 prefix.

        Args:
            prefix: S3 prefix to list files from

        Returns:
            List of file metadata dicts with keys: key, size, last_modified

        Raises:
            Exception: If S3 list operation fails
        """
        response = self.s3_service.s3_client.list_objects_v2(
            Bucket=self.s3_service.bucket,
            Prefix=prefix
        )

        files = []
        if 'Contents' in response:
            for obj in response['Contents']:
                # Only include actual files (not directories)
                if not obj['Key'].endswith('/'):
                    files.append({
                        'key': obj['Key'],
                        'size': obj['Size'],
                        'last_modified': obj['LastModified']
                    })

        return files

    def key_exists(self, s3_key: str) -> bool:
        """Check if S3 key exists.

        Args:
            s3_key: S3 key to check

        Returns:
            True if key exists, False otherwise
        """
        return self.s3_service.file_exists(s3_key)

    def delete_file(self, s3_key: str) -> None:
        """Delete file from S3.

        Args:
            s3_key: S3 key (path) to delete

        Raises:
            Exception: If S3 delete fails
        """
        self.s3_service.s3_client.delete_object(
            Bucket=self.s3_service.bucket,
            Key=s3_key
        )
