#!/Users/sij/miniforge3/bin/python

import os
import sys
import argparse

def ask_for_confirmation(message):
    while True:
        user_input = input(message + " (y/n): ").strip().lower()
        if user_input in ('y', 'n'):
            return user_input == 'y'
        else:
            print("Invalid input. Please enter 'y' or 'n'.")

def rename_files_orig(root_dir, manual):
    for dirpath, _, filenames in os.walk(root_dir, followlinks=False):
        for filename in filenames:
            if '(orig)' in filename:
                orig_filepath = os.path.join(dirpath, filename)
                base_filename, ext = os.path.splitext(filename)
                new_filename = base_filename.replace('(orig)', '')
                new_filepath = os.path.join(dirpath, new_filename + ext)

                if os.path.exists(new_filepath):
                    new_file_new_name = new_filename + '(new)' + ext
                    new_file_new_path = os.path.join(dirpath, new_file_new_name)

                    if manual:
                        if not ask_for_confirmation(f"Do you want to rename {new_filepath} to {new_file_new_path}?"):
                            continue

                    if os.path.exists(new_file_new_path):
                        print(f"Error: Cannot rename {new_filepath} to {new_file_new_path} because the target file already exists.")
                        continue

                    os.rename(new_filepath, new_file_new_path)
                    print(f'Renamed: {new_filepath} -> {new_file_new_name}')
                else:
                    print(f"No associated file found for: {orig_filepath}")

                orig_file_new_name = new_filename + ext
                orig_file_new_path = os.path.join(dirpath, orig_file_new_name)

                if manual:
                    if not ask_for_confirmation(f"Do you want to rename {orig_filepath} to {orig_file_new_path}?"):
                        continue

                if os.path.exists(orig_file_new_path):
                    print(f"Error: Cannot rename {orig_filepath} to {orig_file_new_path} because the target file already exists.")
                    continue

                os.rename(orig_filepath, orig_file_new_path)
                print(f'Renamed: {orig_filepath} -> {orig_file_new_name}')

def rename_files_new(root_dir, manual):
    for dirpath, _, filenames in os.walk(root_dir, followlinks=False):
        for filename in filenames:
            if '(new)' in filename:
                new_filepath = os.path.join(dirpath, filename)
                base_filename, ext = os.path.splitext(filename)
                orig_filename = base_filename.replace('(new)', '')
                orig_filepath = os.path.join(dirpath, orig_filename + ext)

                if os.path.exists(orig_filepath):
                    orig_file_orig_name = orig_filename + '(orig)' + ext
                    orig_file_orig_path = os.path.join(dirpath, orig_file_orig_name)

                    if manual:
                        if not ask_for_confirmation(f"Do you want to rename {orig_filepath} to {orig_file_orig_path}?"):
                            continue

                    if os.path.exists(orig_file_orig_path):
                        print(f"Error: Cannot rename {orig_filepath} to {orig_file_orig_path} because the target file already exists.")
                        continue

                    os.rename(orig_filepath, orig_file_orig_path)
                    print(f'Renamed: {orig_filepath} -> {orig_file_orig_name}')
                else:
                    print(f"No associated file found for: {new_filepath}")

                new_file_new_name = orig_filename + ext
                new_file_new_path = os.path.join(dirpath, new_file_new_name)

                if manual:
                    if not ask_for_confirmation(f"Do you want to rename {new_filepath} to {new_file_new_path}?"):
                        continue

                if os.path.exists(new_file_new_path):
                    print(f"Error: Cannot rename {new_filepath} to {new_file_new_path} because the target file already exists.")
                    continue

                os.rename(new_filepath, new_file_new_path)
                print(f'Renamed: {new_filepath} -> {new_file_new_name}')

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Rename files based on given criteria.')
    parser.add_argument('-o', '--orig', action='store_true', help='Rename files ending with (orig)')
    parser.add_argument('-n', '--new', action='store_true', help='Rename files ending with (new)')
    parser.add_argument('-m', '--manual', action='store_true', help='Manual mode: ask for confirmation before each renaming')
    parser.add_argument('directory', nargs='?', default=os.getcwd(), help='Directory to start the search (default: current directory)')
    args = parser.parse_args()

    if args.orig and args.new:
        print("Error: Please specify either -o or -n, not both.")
        sys.exit(1)

    if args.orig:
        print("Running in ORIG mode")
        rename_files_orig(args.directory, args.manual)
    elif args.new:
        print("Running in NEW mode")
        rename_files_new(args.directory, args.manual)
    else:
        print("Error: Please specify either -o or -n.")
        sys.exit(1)