import boto3
import json
from botocore.exceptions import ClientError

# --- Your existing setup for assuming the role ---
role_arn = "arn:aws:iam::334835636290:role/quiklrn_lambda"
session_name = "AssumeRoleSession1"
region = "ap-south-1"  # Replace with your AWS region

# --- DynamoDB and file-specific variables to be updated ---
dynamodb_table_name = "quiz"  # 👈 Replace with your DynamoDB table name
quiz_name = "test01-09-2025-09:40"  # 👈 Replace with the actual quiz name
host_college_id = "1"  # 👈 Replace with the actual college ID
quiz_id = "3"  # 👈 Replace with the actual quiz ID


# --- S3 variables ---
s3_bucket_name = "quiklrnexam"
file_path = "output.csv"
s3_file_key = "output.csv"

try:
    # Assume the role
    sts_client = boto3.client('sts')
    assumed_role_object = sts_client.assume_role(
        RoleArn=role_arn,
        RoleSessionName=session_name
    )
    credentials = assumed_role_object['Credentials']

    # Create a new session with the temporary credentials
    session = boto3.Session(
        aws_access_key_id=credentials['AccessKeyId'],
        aws_secret_access_key=credentials['SecretAccessKey'],
        aws_session_token=credentials['SessionToken'],
        region_name=region
    )

    # --- S3 File Upload ---
    s3_client = session.client('s3')
    print("Uploading file to S3...")
    s3_client.upload_file(file_path, s3_bucket_name, s3_file_key)
    print("File uploaded successfully!")

    # Construct the S3 file URL
    file_url = f"https://{s3_bucket_name}.s3.{region}.amazonaws.com/{s3_file_key}"
    print(f"S3 file URL: {file_url}")

    # --- DynamoDB Data Storage ---
    dynamodb = session.resource('dynamodb')
    table = dynamodb.Table(dynamodb_table_name)
    print("Storing metadata in DynamoDB...")

    response = table.put_item(
        Item={
            'quiz_file_link': file_url,
            'quiz_name': quiz_name,
            'host_college_id': host_college_id,
            'quiz_id': quiz_id
        }
    )

    # Check the DynamoDB response for success
    if response['ResponseMetadata']['HTTPStatusCode'] == 200:
        print("Metadata successfully stored in DynamoDB.")
    else:
        print("Failed to store metadata in DynamoDB.")
        print(response)

except ClientError as e:
    print(f"An AWS client error occurred: {e.response['Error']['Code']}")
    print(f"Error message: {e.response['Error']['Message']}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")