#!/usr/bin/env python3
"""AWS IAM for agents: two agents share one IAM role; S3 and CloudTrail still tell them apart.

Runs against the deployed POC (make deploy in this kit creates the workload identity
provider and template, the two AgentCore runtimes agentA and agentB, the bucket and its
policy, and a trail for S3 data events).

Needs: boto3 1.44.17 or later. Tested with 1.44.17: pip install boto3==1.44.17
       (that exact release: https://pypi.org/project/boto3/1.44.17/). Older releases do not
       have the workload identity operations.
       AWS credentials for the account that holds the POC.
       To call the new IAM operations from the AWS CLI instead (for example
       aws iam create-workload-identity-provider) you need AWS CLI 2.43.1 or later, the first
       release whose changelog lists them. Installers for that exact version:
         macOS    https://awscli.amazonaws.com/AWSCLIV2-2.43.1.pkg
         Linux    https://awscli.amazonaws.com/awscli-exe-linux-x86_64-2.43.1.zip
         Windows  https://awscli.amazonaws.com/AWSCLIV2-2.43.1.msi
       AWS CLI 2.37.0 was checked and does not have them. This script does not use the CLI.

Run:   python3 quickstart.py
"""
import datetime
import json
import re
import sys
import time
import uuid

import boto3

TESTED_BOTO3 = "1.44.17"  # https://pypi.org/project/boto3/1.44.17/
if tuple(int(part) for part in boto3.__version__.split(".")[:3]) < (1, 44, 17):
    print(f"warning: boto3 {boto3.__version__} is older than the tested {TESTED_BOTO3}; "
          f"if a call is rejected, run: pip install boto3=={TESTED_BOTO3}", file=sys.stderr)

REGION = "us-east-1"
TRAIL_LOG_GROUP = "/field-kit-aws-iam-for-agents/cloudtrail"
mask = lambda text: re.sub(r"\b\d{12}\b", "<account>", str(text))  # keeps output safe to share

control = boto3.client("bedrock-agentcore-control", region_name=REGION)
runtime = boto3.client("bedrock-agentcore", region_name=REGION)
cloudtrail = boto3.client("cloudtrail", region_name=REGION)
logs = boto3.client("logs", region_name=REGION)

runtimes = {r["agentRuntimeName"]: r["agentRuntimeArn"] for r in control.list_agent_runtimes()["agentRuntimes"]}
started = datetime.datetime.now(datetime.timezone.utc)

# 1. Same request to both agents. They run the same code with the same execution role.
for name in ("agentA", "agentB"):
    response = runtime.invoke_agent_runtime(
        agentRuntimeArn=runtimes[name],
        runtimeSessionId=str(uuid.uuid4()),
        payload=json.dumps({"prompt": "read the object"}).encode(),
    )
    body = response["response"].read().decode()
    if "text/event-stream" in response.get("contentType", ""):
        body = "\n".join(line[6:] for line in body.splitlines() if line.startswith("data: "))
    result = json.loads(body)
    result = json.loads(result) if isinstance(result, str) else result
    outcome = f"ALLOWED: {result['content']}" if result["result"] == "allowed" else f"DENIED ({result['error']})"
    print(f"{name}  GetObject {result['object']}  ->  {outcome}")

# 2. CloudTrail: which runtime was given which role session (management events, Event history).
print("\nWaiting for CloudTrail (usually 2 to 5 minutes)...")
sessions = {}
deadline = time.time() + 900
while len(sessions) < 2 and time.time() < deadline:
    time.sleep(30)
    events = cloudtrail.lookup_events(
        LookupAttributes=[{"AttributeKey": "EventName", "AttributeValue": "GetIAMWorkloadIdentityCredentials"}],
        StartTime=started - datetime.timedelta(seconds=60),
    )["Events"]
    for item in events:
        event = json.loads(item["CloudTrailEvent"])
        agent = next(r["ARN"] for r in event["resources"] if r["type"] == "AWS::BedrockAgentCore::Runtime")
        sessions[event["requestParameters"]["roleSessionName"]] = agent

print("\nIdentity issued (GetIAMWorkloadIdentityCredentials):")
for role_session, agent in sessions.items():
    print(f"  role session {role_session}  ->  {mask(agent)}")

# 3. The S3 calls themselves (data events from the kit's trail), joined on the role session name.
print("\nS3 GetObject data events:")
reads = []
while len(reads) < 2 and time.time() < deadline:
    reads = [
        json.loads(e["message"])
        for e in logs.filter_log_events(
            logGroupName=TRAIL_LOG_GROUP,
            startTime=int((started.timestamp() - 60) * 1000),
            filterPattern='{ $.eventName = "GetObject" }',
        )["events"]
    ]
    reads = [e for e in reads if e["userIdentity"]["arn"].split("/")[-1] in sessions]
    if len(reads) < 2:
        time.sleep(30)
for event in reads:
    role_session = event["userIdentity"]["arn"].split("/")[-1]
    agent = sessions[role_session].split("/")[-1]
    print(f"  {event['eventTime']}  {event.get('errorCode', 'allowed'):<13} {role_session}  ->  {agent}")
