import argparse
import glob
import os

def concatenate_messages_files(directory, output_file):
    """
    Concatenates all 'messages.*' files in a directory into a new file,
    in reverse order of their numeric suffix (if present).

    Args:
        directory (str): The path to the directory containing the message files.
        output_file (str): The path to the output file where the concatenated
            content will be written.
    """
    messages_files = glob.glob(os.path.join(directory, "messages*"))

    # Filter out the base "messages" file and sort the rest numerically in reverse order
    numbered_files = []
    base_message_file = ""
    for f in messages_files:
        if f == os.path.join(directory, "messages"):
            base_message_file = f
        else:
            try:
                # Extract the numeric suffix and use it for sorting
                suffix = int(f.split(".")[-1])
                numbered_files.append((f, suffix))
            except ValueError:
                # Handle files without a numeric suffix (e.g., "messages")
                pass

    numbered_files.sort(key=lambda x: x[1], reverse=True)  # Sort by numeric suffix, descending
    sorted_files = [f for f, _ in numbered_files] # Extract file paths

    # Add the base messages file to the beginning of the list
    if base_message_file:
        sorted_files.append(base_message_file)

    try:
        with open(output_file, "w") as outfile:
            for f in sorted_files:
                print(f'Concatenating {f}')
                with open(f, "r") as infile:
                    outfile.write(infile.read())
            print(f"Successfully concatenated messages files in reverse order to '{output_file}'.")

    except FileNotFoundError as e:
        print(f"Error: A file was not found: {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
            description="Concatenate messages.* files in reverse order.",
            formatter_class=argparse.ArgumentDefaultsHelpFormatter,
            )
    parser.add_argument(
        "directory",
        help="The directory containing the messages.* files."
    )
    parser.add_argument(
        "-o",
        "--output",
        default="messages.all",
        help="The name of the output file (default: messages.all)."
    )

    args = parser.parse_args()

    log_directory = args.directory
    output_log_file = os.path.join(args.directory, args.output)

    concatenate_messages_files(log_directory, output_log_file)
