#!/usr/bin/python3
import os
import sys


def remove_suffix_back(directory, suffix):
    """Removes the specified suffix from the end of filenames before the extension."""
    for filename in os.listdir(directory):
        filepath = os.path.join(directory, filename)

        # Skip directories
        if not os.path.isfile(filepath):
            continue

        # Separate base name and extension
        base, ext = os.path.splitext(filename)

        # Remove suffix from the back of the base name
        if base.endswith(suffix):
            new_name = base[: -len(suffix)] + ext
            os.rename(filepath, os.path.join(directory, new_name))
            print(f"Renamed: {filename} -> {new_name}")


def remove_prefix_front(directory, prefix):
    """Removes the specified prefix from the start of filenames."""
    for filename in os.listdir(directory):
        filepath = os.path.join(directory, filename)

        # Skip directories
        if not os.path.isfile(filepath):
            continue

        # Remove prefix if it exists
        if filename.startswith(prefix):
            new_name = filename[len(prefix):]
            os.rename(filepath, os.path.join(directory, new_name))
            print(f"Renamed: {filename} -> {new_name}")


def remove_from_extension(directory, suffix):
    """Removes the specified string from the file extensions."""
    for filename in os.listdir(directory):
        filepath = os.path.join(directory, filename)

        # Skip directories
        if not os.path.isfile(filepath):
            continue

        # Separate base name and extension
        base, ext = os.path.splitext(filename)

        # Remove suffix from the extension
        if ext.endswith(suffix):
            new_ext = ext[: -len(suffix)]
            new_name = base + new_ext
            os.rename(filepath, os.path.join(directory, new_name))
            print(f"Renamed: {filename} -> {new_name}")


def main():
    # Validate arguments
    if len(sys.argv) < 3:
        print("Usage: deappend.py <mode> <string> [directory]")
        sys.exit(1)
    import subprocess
    subprocess.run(["python", "/home/honney/.bin/tracker.py", "add", "deappend"])

    # Get arguments
    mode = sys.argv[1]  # Mode: back, front, ext/extension
    string = sys.argv[2]  # String to remove
    directory = sys.argv[3] if len(sys.argv) > 3 else os.getcwd()  # Default: current directory

    # Check that the string is not empty
    if string == "":
        print("Error: The string to remove cannot be empty.")
        sys.exit(1)

    # Validate directory
    if not os.path.isdir(directory):
        print(f"Error: Directory '{directory}' does not exist.")
        sys.exit(1)

    # Process based on mode
    if mode == "back":
        remove_suffix_back(directory, string)
    elif mode == "front":
        remove_prefix_front(directory, string)
    elif mode == "ext" or mode == "extension":
        remove_from_extension(directory, string)
    else:
        print(f"Error: Unsupported mode '{mode}'. Supported modes: front, back, ext/extension.")
        sys.exit(1)


if __name__ == "__main__":
    main()
