import argparse
import os
import re

log_class = []
log_level = []
log_pattern = []


def scan_dir(dir_path):
    file_list = os.listdir(dir_path)
    for filename in file_list:
        file_path = os.path.join(dir_path, filename)
        if os.path.isfile(file_path) and (filename.endswith('.java') or filename.endswith('.kt')):
            process_file(file_path)
        elif os.path.isdir(file_path):
            scan_dir(file_path)


def process_file(file_path):
    new_lines = []
    record_lines = []
    stack = []

    # 使用 utf-8 进行文件读取，以防编码问题
    with open(file_path, 'r+', encoding='utf-8') as file:
        hiting = False
        match = None

        for line in file.readlines():

            if hiting is False:
                match = re.match(
                    r'\s+(%s)\s*\.\s*(%s)\s*\(' % ('|'.join(log_class), '|'.join(log_level)), line)
                if match is not None:
                    hiting = True
                else:
                    new_lines.append(line)
                    continue

            record_lines.append(' - ' + line)

            for letter in line.strip():
                if len(stack) == 0:
                    if letter == '(':
                        stack.append(letter)
                elif stack[-1] == '"':
                    if letter == '"':
                        stack.pop()
                elif stack[-1] == '(':
                    if letter == '"':
                        stack.append(letter)
                    elif letter == '(':
                        stack.append(letter)
                    elif letter == ')':
                        stack.pop()

                        if len(stack) == 0:
                            replace = match.group()
                            if file_path.endswith('.java'):
                                replace += '"TAG", "");'
                            elif file_path.endswith('.kt'):
                                replace += '"TAG", "")'
                            replace += '\n'

                            # new_lines.append(replace)
                            # record_lines.append(' + ' + replace + '\n')

                            new_lines.append('\n')
                            record_lines.append(' + \n')

                            match = None
                            hiting = False
                            break

        if len(record_lines) > 0:
            record_file.write(
                '--------------------------------------------------------------------\n')
            record_file.write(file_path + '\n')
            record_file.writelines(record_lines)

            file.seek(0)
            file.truncate()
            file.writelines(new_lines)


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-c', '--log_class', type=str, help='log class', required=True)
    parser.add_argument('-l', '--log_level', type=str, help='log level', required=True)
    args = parser.parse_args()

    log_class = args.log_class.split()
    log_level = args.log_level.split()

    print("remove class: " + str(log_class))
    print("remove level: " + str(log_level))

    with open('proguard_log.txt', 'w', encoding='utf-8') as record_file:
        # 获取父目录，确保路径跨平台可用
        cwd = os.path.abspath(os.path.join(os.getcwd(), os.pardir))
        print("cwd: " + cwd)
        scan_dir(cwd)
