import os
import datetime
import time

# Define the paths to the two folders
ts_folder_path = '2m/2m_hls'
image_folder_path = '2m/iframe_live'

# Define the time delay between executions (in seconds)
delay_seconds = 28800  # 4 hour (3600 seconds)

while True:
    # Calculate the time threshold (2 hours ago from the current time)
    current_time = datetime.datetime.now()
    threshold_time = current_time - datetime.timedelta(hours=2)

    # Function to delete files created within the last 2 hours
    def delete_files_in_folder(folder_path, file_extension):
        for root, dirs, files in os.walk(folder_path):
            for file in files:
                if file.endswith(file_extension):
                    file_path = os.path.join(root, file)
                    file_creation_time = datetime.datetime.fromtimestamp(os.path.getctime(file_path))
                    if file_creation_time > threshold_time:
                        try:
                            os.remove(file_path)
                            print(f"Deleted: {file_path}")
                        except Exception as e:
                            print(f"Error deleting {file_path}: {str(e)}")

    # Delete .ts files in the first folder
    delete_files_in_folder(ts_folder_path, '.ts')

    # Delete images in the second folder
    delete_files_in_folder(image_folder_path, '.png')

    print("Deletion process completed. Waiting for the next execution...")

    # Delay before the next execution
    time.sleep(delay_seconds)
