import json
from decouple import config

try:
    import boto3
except ImportError as e:
    print("Did not find boto3 module, installing it")
    import subprocess
    subprocess.call(["pip3", "install", "boto3"])
    import boto3
    print("Installation complete.")

 

# Define the AWS region and service
AWS_REGION            = config("AWS_REGION", default="us-west-2", cast=str)
AWS_SERVICE           = config("AWS_SERVICE", default="rekognition", cast=str)

# Set the AWS access key and secret access key
AWS_ACCESS_KEY_ID     = config("AWS_ACCESS_KEY_ID", default="", cast=str)
AWS_SECRET_ACCESS_KEY = config("AWS_SECRET_ACCESS_KEY", default="", cast=str)


def save_result(data ,output_file):
    # Load the existing data from the file if it exists
    try:
        with open(output_file, 'r') as file:
            existing_data = json.load(file)
    # 
    except FileNotFoundError:
        existing_data = []
    # 
    # os.remove(output_file)
    # wait_until_file_not_open(output_file)
    # 
    existing_data.append(data)    
    # 
    with open(output_file, 'w') as file:
            json.dump(existing_data, file)

def detect_labels_in_frame(frame_path, counter=0, frame_duration=""):
    # Initialize the Amazon Rekognition client :: Connect to AWS service using boto3
    client = boto3.client(
        AWS_SERVICE,
        aws_access_key_id=AWS_ACCESS_KEY_ID,
        aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
        region_name=AWS_REGION
    )
    # Read The image as a bytes object and pass it to AWS Rekognition detect_labels() Function
    with open(frame_path, 'rb') as image:
        response = client.detect_labels(
            Image={
                'Bytes': image.read()
            }
        )
    # Remove The File 
    os.remove(frame_path)
    # return The Result
    return {"frame_id":counter, "frame_time":frame_duration, "response":response["Labels"]}


if __name__ == '__main__':  

    import os
    import argparse
    import mimetypes

    # Create an argument parser
    parser = argparse.ArgumentParser()
    # Add the argument for the video path
    parser.add_argument("-i", "--input", type=str, help="The path to the video file", required=True)
    # Add the argument for frame id
    parser.add_argument("-f", "--frame-id", type=int, default=0)
    # Add the argument for frame duration
    parser.add_argument("-d", "--frame-duration", type=str, default="00:00:00.000")
    # Add the argument for saving the result video
    parser.add_argument("-s", "--output-path", type=str, default="demo.json")
    # Parse the command line arguments
    args = parser.parse_args()

    # 
    try:
        # 
        if not args.input:
            raise ValueError("[Error][Message : Input Path is Required, Please Provide Input Path.]")
        # 
        if not os.path.exists(args.input):
            print(f"[Error][< {args.input} >][Message : The Target Directory Doesn't Exist.]")
            raise SystemExit(1)
        # 
        if not os.path.isfile(args.input):
            print(f"[Error][< {args.input} >][Message : The Input Path Is Not A File.]")
            raise SystemExit(1)
        #
        if not mimetypes.guess_type(args.input)[0].startswith("image"):
            print(f"[Error][< {args.input}>][Message : The Input Path Is Not A Valid Image File.]")
            raise SystemExit(1)
        # 
        data = detect_labels_in_frame(args.input, args.frame_id, args.frame_duration)
        # # 
        # wait_until_file_not_open(args.output_path)
        # save_result(data, args.output_path)

        output_path = f"{args.output_path}/{args.frame_id}.json"
        
        with open(output_path, 'w') as file:
            json.dump(data, file)
    # 
    except ValueError as ve:
        print(ve)
        parser.print_help()
    # 
    except Exception as e:
        print(f"An error occurred: {e}")