import boto3
import json
import os
import random
import re
import time
from urllib.parse import unquote_plus
from slack_helper import get_user_info
from slack_helper import post_message
from slack_helper import route_message_to_channel
from comprehend_helper import classify_document

region = os.environ['REGION']
bucketName = os.environ['BUCKETNAME']
firehose_client = boto3.client(service_name='firehose')
s3_client = boto3.client('s3', region_name=region)
s3 = boto3.resource('s3')

def lambda_handler(event, context):
    # Get the object from the event
    bucketName = event['Records'][0]['s3']['bucket']['name']
    keyName = unquote_plus(event['Records'][0]['s3']['object']['key'])
    fileName = keyName[keyName.rindex('/')+1:]
    
    print(f"Bucket: {bucketName} key:{keyName} file:{fileName}")

    # Read the S3 Object
    bucket = s3.Bucket(bucketName)
    body = bucket.Object(keyName).get()['Body'].read().decode("utf-8", 'ignore')
    records= body.split('\n')
    for record in records:
        if len(record.strip()) > 0:
            jsonBody = json.loads(record)
            print("Body = ")
            print(jsonBody)
            user = jsonBody["user"]
            ts = jsonBody['ts']
            text = jsonBody["text"]
            
            if len(text)<=0:
                print(f"Ignoring message - {text}")
                continue
            
            if user != 'USLACKBOT':
                response = get_user_info(user)
                text = re.sub(r'<.+>', '', text)
                tag = classify_document(text)
                print(tag)
                nums = ['0','1','2','3','4','5','6','7','8','9']
                randomString =  ''.join(random.choice(nums) for i in range(6))
                post_message(f"Your request has been received and assigned to {tag} group, Your ticket number is TKT-{randomString}.",ts)
                route_message_to_channel(f"TKT-{randomString}: {text}",tag)
    return {
        'statusCode': 200,
        'body': json.dumps('Success')
    }
