# Import the modules
from couchbase.cluster import Cluster
from couchbase.cluster import PasswordAuthenticator
import json
"""
Get credentials from Kubernetes. The credentials were set up as a dictionary. For example:
{
    "username": "USERNAME",
    "password": "PASSWORD"
}
"""
credentials = None
with open('/var/run/secrets/user_credentials/couchbase_credentials') as f:
 credentials = json.load(f)
# Verify the credentials were pulled correctly
if credentials:
    # Try the connection and pass in authentication details
    bucket = None
    try:
        cluster = Cluster(f"couchbase://{credentials.get('hostname')}")
        cluster.authenticate(
            PasswordAuthenticator(
                credentials.get('username'),
                credentials.get('password')
            )
        )
        bucket = cluster.open_bucket('beer-sample')
    except Exception as e:
        print(f'There was an error connecting to the bucket: {e}')
    # Confirm the bucket is connected
    if bucket and bucket.connected:
        # Get a value from the bucket by index and print out the result
        print(json.dumps(bucket.get('21st_amendment_brewery_cafe').value, indent=4))
        # Close connection
        bucket._close()