import argparse
import json
import boto3
import os
from botocore.exceptions import ClientError, NoCredentialsError
import logging

# Initialize logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

def check_s3_permissions(bucket_name, object_name):
    s3 = boto3.client('s3')
    permissions_to_check = ['s3:GetObject', 's3:PutObject']
    results = {}
    for permission in permissions_to_check:
        try:
            if permission == 's3:GetObject':
                s3.head_object(Bucket=bucket_name, Key=object_name)
                results[permission] = "Permission Granted"
            elif permission == 's3:PutObject':
                s3.put_object(Bucket=bucket_name, Key=object_name, Body=b'')
                s3.delete_object(Bucket=bucket_name, Key=object_name)
                results[permission] = "Permission Granted"
        except ClientError as e:
            if e.response['Error']['Code'] in ['403', 'AccessDenied']:
                results[permission] = "Permission Denied"
            else:
                results[permission] = f"Error checking permission: {e}"
    return results

def download_from_s3(bucket_name, object_name, local_file_path):
        #boto3.setup_default_session(profile_name='US')
        s3 = boto3.client('s3')
        try:
            s3.head_object(Bucket=bucket_name, Key=object_name)
            s3.download_file(bucket_name, object_name, local_file_path)
            logging.debug(f"File downloaded from S3: {object_name}")
            return True
        except ClientError as e:
            logging.error(f"An error occurred while downloading: {e}")
            return False

def upload_to_s3(file_path, bucket_name, object_name):
    if 's3:PutObject' in check_s3_permissions(bucket_name, object_name) and check_s3_permissions(bucket_name, object_name)['s3:PutObject'] == "Permission Granted":
        s3 = boto3.client('s3')
        try:
            s3.upload_file(file_path, bucket_name, object_name)
            logging.debug(f"File {file_path} uploaded to bucket {bucket_name} as {object_name}")
        except NoCredentialsError:
            logging.error("Credentials not available for AWS S3.")
        except Exception as e:
            logging.error(f"An error occurred during upload: {e}")
    else:
        logging.error("Insufficient permissions to upload the file.")

def log_to_dictionary(input_strings):
    dictionary = {}
    bucket_name = os.getenv('AWS_S3_BUCKET_NAME', 'p81-devops')
    s3_object_name = os.getenv('AWS_S3_OBJECT_NAME', 'dictionary.json')
    file_path = s3_object_name
    if not bucket_name or not s3_object_name:
        logging.error("S3 bucket name and object name must be set in environment variables.")
        return

    download_from_s3(bucket_name, s3_object_name, file_path)
    try:
        with open(file_path, 'r') as file:
            dictionary = json.load(file)
    except json.JSONDecodeError:
        logging.warning("Error decoding JSON. Starting with a new dictionary.")

    for input_string in input_strings:
        logging.debug(f"Processing input string: {input_string}")
        parts = input_string.split('-', 1)
        logging.debug(f"Part split name: {parts}")
        if len(parts) < 2:
            logging.warning(f"Error: The input string '{input_string}' must contain at least one hyphen.")
            continue

        key = parts[1]
        val = parts[0]
        logging.debug(f"Inserting to dictionary >>> Key: {key}, val: {val}")
        dictionary[key] = input_string

    with open(file_path, 'w') as file:
        json.dump(dictionary, file, indent=4)

    upload_to_s3(file_path, bucket_name, s3_object_name)
    logging.debug("Updated dictionary uploaded.")

def main():
    inputs = os.getenv('NEW_VERSIONS', '')
    new_inputs = inputs.strip().split(" ")
    logging.debug(f"Starting with inputs: {new_inputs}")
    log_to_dictionary(new_inputs)

if __name__ == "__main__":
    main()
