import os
import argparse

def main():
    # argparse를 사용하여 명령줄 인수 처리
    parser = argparse.ArgumentParser(description="Set outline thickness")
    parser.add_argument("--thickness", type=int, help="Thickness of outline (0 - no outline, 255 - maximum outline)")
    args = parser.parse_args()

    # argparse를 통해 입력받은 값이 있다면 사용하고, 없으면 input으로 값을 입력받습니다.
    if args.thickness is not None:
        t = args.thickness
    else:
        t = input("Enter the thickness of outline (0 - no outline, 255 - maximum outline): ")
        try:
            t = int(t)
        except ValueError:
            print("ERROR: Invalid input. Please enter a valid integer between 0 and 255. Exiting")
            return

    # 현재 디렉토리와 그 하위 디렉토리에서 "Texcoord.buf" 파일을 검색합니다.
    texcoord_files = []
    for root, dirs, files in os.walk(os.getcwd()):
        for file in files:
            if "Texcoord.buf" in file:
                texcoord_files.append(os.path.join(root, file))

    if not texcoord_files:
        print("ERROR: unable to find texcoord file. Ensure you have 'Texcoord.buf' file in the directory or its subdirectories. Exiting")
        return

    # 현재 디렉토리와 그 하위 디렉토리에서 ".ini" 파일을 검색합니다.
    ini_files = []
    for root, dirs, files in os.walk(os.getcwd()):
        for file in files:
            if file.endswith(".ini"):
                ini_files.append(os.path.join(root, file))

    if not ini_files:
        print("ERROR: unable to find .ini file. Ensure you have a '.ini' file in the directory or its subdirectories. Exiting")
        return

    for texcoord_file in texcoord_files:
        for ini_file in ini_files:
            with open(ini_file, "r") as f:
                stride = int(f.read().split(os.path.basename(texcoord_file))[0].split("\n")[-2].split("=")[1].strip())

            print(f"Texcoord: {texcoord_file}, Ini: {ini_file}, Stride: {stride}")

            with open(texcoord_file, "rb+") as f:
                print("Removing outlines")
                data = bytearray(f.read())
                i = 0
                while i < len(data):
                    data[i+3] = t
                    i += stride

                print("Writing results to new file")
                f.seek(0)
                f.write(data)
                f.truncate()

    print("All operations complete, exiting")

if __name__ == "__main__":
    main()
