import boto3

# Create an SSM client
ssm = boto3.client('ssm')

# Initialize global variables
REKOGNITION_MODEL_ARN = None
PROJECT_ARN = None
VERSION_NAME = None

def get_parameter(name):
    params = {
        'Name': name,
        'WithDecryption': True
    }
    response = ssm.get_parameter(**params)
    return response['Parameter']['Value']

def lambda_handler(event, context):  
    global REKOGNITION_MODEL_ARN, PROJECT_ARN,VERSION_NAME
    if PROJECT_ARN is None or VERSION_NAME is None or REKOGNITION_MODEL_ARN is None:
        PROJECT_ARN = get_parameter('/datafy-rekognition-stack/project-arn')
        VERSION_NAME = get_parameter('/datafy-rekognition-stack/model-version-name')
        REKOGNITION_MODEL_ARN = get_parameter('/datafy-rekognition-stack/model-arn')

    model_result = start_model()
    result = {
        "started": model_result 
    }
    return result


def start_model():
    min_inference_units=1
    client=boto3.client('rekognition')

    try:
        # Start the model
        print('Starting model: ' + REKOGNITION_MODEL_ARN)
        response=client.start_project_version(ProjectVersionArn=REKOGNITION_MODEL_ARN, MinInferenceUnits=min_inference_units)
        # Wait for the model to be in the running state
        project_version_running_waiter = client.get_waiter('project_version_running')
        project_version_running_waiter.wait(ProjectArn=PROJECT_ARN, VersionNames=[VERSION_NAME])

        #Get the running status
        describe_response=client.describe_project_versions(ProjectArn=PROJECT_ARN,
            VersionNames=[VERSION_NAME])
        for model in describe_response['ProjectVersionDescriptions']:
            print("Status: " + model['Status'])
            print("Message: " + model['StatusMessage']) 
        return "Started"
    except Exception as e:
        print(e)
        return e
        