"""Reads one S3 object and reports what happened.

Both demo runtimes run this same file with the same execution role. The only
difference between them is the identity AWS attaches to their credentials.
"""
from bedrock_agentcore import BedrockAgentCoreApp  # import before boto3

import os

import boto3
from botocore.exceptions import ClientError

app = BedrockAgentCoreApp()


@app.entrypoint
def handler(payload, context):
    # Created after the bedrock_agentcore import, so the client uses the
    # credentials that carry the agent's identity.
    s3 = boto3.client("s3", region_name=os.environ["DEMO_REGION"])
    result = {"agent": os.environ["AGENT_NAME"], "object": f"s3://{os.environ['DEMO_BUCKET']}/{os.environ['DEMO_KEY']}"}
    try:
        obj = s3.get_object(Bucket=os.environ["DEMO_BUCKET"], Key=os.environ["DEMO_KEY"])
        return {**result, "result": "allowed", "content": obj["Body"].read().decode().strip()}
    except ClientError as e:
        return {**result, "result": "denied", "error": e.response["Error"]["Code"]}


if __name__ == "__main__":
    app.run()
