# SPDX-License-Identifier: Apache-2.0
# Copyright 2025 S3 Fetch Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
Example configuration and usage patterns for S3 fetching.
This demonstrates how to use the S3Fetcher class with different scenarios.

CREDENTIAL CONFIGURATION:
The S3Fetcher class uses secure credential management. Configure credentials using one of these methods:

1. Environment Variables:
   export AWS_ACCESS_KEY_ID="your-access-key"
   export AWS_SECRET_ACCESS_KEY="your-secret-key"
   export AWS_DEFAULT_REGION="us-east-1"

2. AWS CLI Configuration:
   aws configure

3. AWS Credential Files (~/.aws/credentials):
   [default]
   aws_access_key_id = your-access-key
   aws_secret_access_key = your-secret-key
   region = us-east-1

4. IAM Roles (for EC2 instances or Lambda functions)

5. AWS SSO or other credential providers
"""

from s3_fetch import S3Fetcher
import os

def example_credential_configuration():
    """Example showing different ways to configure AWS credentials securely."""
    print("=== Credential Configuration Examples ===")
    
    # Method 1: Using environment variables (recommended for development)
    print("\n1. Environment Variables Method:")
    print("   Set these environment variables before running:")
    print("   export AWS_ACCESS_KEY_ID='your-access-key'")
    print("   export AWS_SECRET_ACCESS_KEY='your-secret-key'")
    print("   export AWS_DEFAULT_REGION='us-east-1'")
    
    # Method 2: AWS CLI configuration
    print("\n2. AWS CLI Configuration:")
    print("   Run: aws configure")
    print("   This creates ~/.aws/credentials and ~/.aws/config files")
    
    # Method 3: IAM Roles (for production)
    print("\n3. IAM Roles (Production Recommended):")
    print("   - For EC2: Attach IAM role to instance")
    print("   - For Lambda: Configure execution role")
    print("   - For ECS/EKS: Use task roles")
    
    # Method 4: Credential files
    print("\n4. AWS Credential Files:")
    print("   Create ~/.aws/credentials with:")
    print("   [default]")
    print("   aws_access_key_id = your-access-key")
    print("   aws_secret_access_key = your-secret-key")
    
    # Initialize fetcher - will use any of the above methods automatically
    try:
        fetcher = S3Fetcher()
        print("\n✅ S3Fetcher initialized successfully with available credentials")
        return fetcher
    except Exception as e:
        print(f"\n❌ Failed to initialize S3Fetcher: {e}")
        print("Please configure AWS credentials using one of the methods above.")
        return None

def example_basic_usage():
    """Basic usage example using secure credential management."""
    print("=== Basic Usage Example ===")
    
    # Initialize S3Fetcher - credentials loaded from environment variables or AWS credential files
    fetcher = S3Fetcher()
    
    # List buckets
    buckets = fetcher.list_buckets()
    print(f"Available buckets: {buckets}")
    
    # Example bucket and object
    bucket_name = "my-example-bucket"
    object_key = "data/sample.txt"
    
    # Get object content
    content = fetcher.get_object_content(bucket_name, object_key)
    if content:
        print(f"Object content: {content[:100]}...")
    
    # Download file
    local_path = "downloaded_sample.txt"
    success = fetcher.download_file(bucket_name, object_key, local_path)
    print(f"Download successful: {success}")

def example_batch_download():
    """Example of downloading multiple files from S3."""
    print("=== Batch Download Example ===")
    
    fetcher = S3Fetcher()
    bucket_name = "my-data-bucket"
    prefix = "logs/"
    
    # List all objects with specific prefix
    objects = fetcher.list_objects(bucket_name, prefix)
    
    # Download each object
    download_dir = "downloads"
    os.makedirs(download_dir, exist_ok=True)
    
    for obj_key in objects:
        local_filename = obj_key.replace("/", "_")
        local_path = os.path.join(download_dir, local_filename)
        
        success = fetcher.download_file(bucket_name, obj_key, local_path)
        print(f"Downloaded {obj_key}: {success}")

def example_metadata_inspection():
    """Example of inspecting object metadata."""
    print("=== Metadata Inspection Example ===")
    
    fetcher = S3Fetcher()
    bucket_name = "my-bucket"
    
    # List objects and get metadata for each
    objects = fetcher.list_objects(bucket_name)
    
    for obj_key in objects[:5]:  # First 5 objects
        metadata = fetcher.get_object_metadata(bucket_name, obj_key)
        if metadata:
            print(f"\nObject: {obj_key}")
            print(f"  Size: {metadata['ContentLength']} bytes")
            print(f"  Type: {metadata['ContentType']}")
            print(f"  Modified: {metadata['LastModified']}")

if __name__ == "__main__":
    # Run examples
    try:
        # First show credential configuration options
        example_credential_configuration()
        print("\n" + "="*50 + "\n")
        
        # Then run the usage examples
        example_basic_usage()
        print("\n" + "="*50 + "\n")
        example_batch_download()
        print("\n" + "="*50 + "\n")
        example_metadata_inspection()
    except Exception as e:
        print(f"Error running examples: {e}")
        print("Make sure to configure valid AWS credentials using environment variables, AWS CLI, or credential files.")