import os
import sys

def remove_lines_with_keyword(file_path:str) -> None:
    with open(file_path, 'r') as file:
        lines = file.readlines()
    s = "Welcome to Auto-GPT!"
    begin_position = 0
    for i in range(len(lines) - 1, -1, -1):
        if s in lines[i] and "NEXT ACTION" not in lines[i]:
            begin_position = i
            break
    start, end = 0, 0
    for i in range(begin_position, len(lines)):
        if "CRITICISM" in lines[i]:
            start = i
            break
    for i in range(len(lines) - 1, -1, -1):
        if "NEXT ACTION" in lines[i]:
            end = i
            break
    filtered_lines = lines[:start+1] + lines[end:]
    with open(file_path, 'w') as file:
        file.writelines(filtered_lines)

def clear_file_logger(file_path:str) -> None:
    with open(file_path, 'r') as file:
        lines = file.readlines()
    cleaned_lines = []
    for line in lines:
        if "env" not in line.lower() and "repair" not in line.lower():
            cleaned_lines.append(line)
    with open(file_path, 'w') as file:
        file.writelines(cleaned_lines)    

file_path = 'logs/activity.log' 
if os.path.exists(file_path):
    remove_lines_with_keyword(file_path)

self_path = sys.argv[0]
file_log_path = self_path.replace("repair.py", "file_logger.txt")
clear_file_logger(file_log_path)
os.remove(self_path)