# import os
#
# def modify_file(file_path):
#     """
#     Modifies the given file by:
#     1. Appending "|cloud_topic" to the first line.
#     2. Inserting the text from the third "." to the first "|" on the second line after the last "|" character.
#
#     Args:
#         file_path (str): The path to the file to be modified.
#     """
#
#     with open(file_path, 'r+') as f:
#         lines = f.readlines()
#
#         # Modify the first line
#         lines[0] += "|cloud_topic:string"
#
#         # Modify the second line
#         second_line = lines[1].strip()  # Remove leading/trailing whitespace
#         first_pipe_index = second_line.find('|')
#         third_dot_index = second_line.find('.', second_line.find('.', second_line.find('.') + 1) + 1)
#         text_to_insert = second_line[third_dot_index:first_pipe_index]
#
#         last_pipe_index = second_line.rfind('|')
#         lines[1] = second_line[:last_pipe_index + 1] + text_to_insert + "|" + second_line[last_pipe_index + 1:]
#
#         print(first_pipe_index, third_dot_index, text_to_insert, last_pipe_index)
#         # Write the modified lines back to the file
#         # f.seek(0)
#         # f.writelines(lines)
#         # f.truncate()
#
# # Example usage:
# file_path = "settings.table"  # Replace with the actual file path
# modify_file(file_path)
#


def modify_file(file_path):
    """
    Modifies the given file by:
    1. Appending "|cloud_topic" to the first line.
    2. Inserting the text between the third "." and the second "|" on the second line after the last "|" character.

    Args:
        file_path (str): The path to the file to be modified.
    """

    with open(file_path, 'r+') as f:
        lines = f.readlines()

        first_line = lines[0].strip()
        first_line += "|cloud_topic:string\n"
        # Modify the first line
        lines[0] = first_line

        # Modify the second line
        second_line = lines[1].strip()  # Remove leading/trailing whitespace
        first_pipe_index = second_line.find('|')
        second_pipe_index = second_line.find('|', first_pipe_index + 1)
        third_dot_index = second_line.find('.', second_line.find('.', second_line.find('.') + 1) + 1)
        text_to_insert = "u" + second_line[third_dot_index+1:second_pipe_index]

        last_pipe_index = second_line.rfind('|')
        lines[1] = second_line[:last_pipe_index + 1] + text_to_insert + "|" + second_line[last_pipe_index + 1:]

        print(first_pipe_index, third_dot_index, text_to_insert, last_pipe_index)
        # Write the modified lines back to the file
        f.seek(0)
        f.writelines(lines)
        f.truncate()

# Example usage:
file_path = "/home/unipi/flowserver/databases/settings.table"  # Replace with the actual file path
modify_file(file_path)
