import os
import time
import boto3
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

# AWS S3 Bucket Details
BUCKET_NAME = 'p81-devops'
CONFIG_FILE_KEY = 'kv_test.json'
LOCAL_CONFIG_PATH = 'config.txt'

def download_config_from_s3():
    """Downloads the configuration file from AWS S3."""
    boto3.setup_default_session(profile_name='US')
    s3 = boto3.client('s3')
    s3.download_file(BUCKET_NAME, CONFIG_FILE_KEY, LOCAL_CONFIG_PATH)

def read_config():
    """Reads the configuration file and updates environment variables."""
    with open(LOCAL_CONFIG_PATH, 'r') as file:
        lines = file.readlines()
    for line in lines:
        line = line.strip()
        if not line or line.startswith('#'):
            continue
        try:
            key, value = line.split('=', 1)
            os.environ[key.strip()] = value.strip()
            print(f"Updated environment: {key.strip()} = {os.environ[key.strip()]}")
        except ValueError:
            print(f"Skipping invalid line: {line}")

class ConfigChangeHandler(FileSystemEventHandler):
    """Handles filesystem changes by re-reading the configuration file."""
    def on_modified(self, event):
        if f"{event.src_path}/{LOCAL_CONFIG_PATH}" == os.path.abspath(LOCAL_CONFIG_PATH):
            print("Configuration file changed. Reloading...")
            read_config()

observer = Observer()
observer.schedule(ConfigChangeHandler(), path='.', recursive=False)
observer.start()

# Initial setup: download and read configuration
download_config_from_s3()
read_config()

def check_s3_for_updates(bucket, key, last_modified):
    s3 = boto3.client('s3')
    response = s3.head_object(Bucket=bucket, Key=key)
    return response['LastModified'] > last_modified

def main():
    s3 = boto3.client('s3')
    response = s3.head_object(Bucket=BUCKET_NAME, Key=CONFIG_FILE_KEY)
    last_modified = response['LastModified']
    try:
        while True:
            if check_s3_for_updates(BUCKET_NAME, CONFIG_FILE_KEY, last_modified):
                print("File has been updated. Reloading...")
                #read_config()
                # Reload your configuration here
                # Update last_modified to the new modification time
                response = s3.head_object(Bucket=BUCKET_NAME, Key=CONFIG_FILE_KEY)
                last_modified = response['LastModified']
                download_config_from_s3()
            time.sleep(60)  # check every minute
    except KeyboardInterrupt:
        observer.stop()
        observer.join()

if __name__ == "__main__":
    main()