import boto3
import json
import requests
from botocore.exceptions import ClientError
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# --- 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"
s3_file_key = f"quiz_{quiz_id}.qquiz"   # 👈 dynamic filename in S3

# --- File download URL (replace with real URL you were generating in JS) ---
file_url_to_download = f"https://awsdev.quiklrn.com/admin/college/quiz.php?method=download&sec_id=3&quiz_id={quiz_id}"

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
    )

    # --- Download file from request ---
    print("Downloading file from request URL...")
    # response = requests.get(file_url_to_download, stream=True)
    response = requests.get(file_url_to_download, stream=True, verify=False)

    response.raise_for_status()  # raise exception if download fails
    file_content = response.content

    # --- S3 File Upload ---
    s3_client = session.client('s3')
    print("Uploading file to S3...")
    s3_client.put_object(Bucket=s3_bucket_name, Key=s3_file_key, Body=file_content)
    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_id': quiz_id,
            'quiz_name': quiz_name,
            'host_college_id': host_college_id,
            'quiz_file_link': file_url
        }
    )

    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}")
