def replace_quotation_marks(language_code):
    quotation_marks_options = [
        ("„", "“"),  # Option 1
        ("«", "»"),  # Option 2
        ("‘", "’"),  # Option 3
        ("「", "」")  # Option 4
    ]

    print("Choose the kind of quotation marks by entering the corresponding number:")
    for i, marks in enumerate(quotation_marks_options, start=1):
        print(f"{i}. {marks[0]}…{marks[1]}")
    
    choice = int(input("Your choice (1-4): ")) - 1
    if choice < 0 or choice >= len(quotation_marks_options):
        print("Invalid choice. Exiting.")
        return

    new_quotes = quotation_marks_options[choice]

    file_path = f"../../../po/{language_code}.po"

    replacement_count = 0

    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            lines = file.readlines()

        updated_lines = []
        inside_msgstr_block = False
        for line in lines:
            if line.startswith('msgstr'):
                inside_msgstr_block = True
                if not line.strip() == 'msgstr ""':
                    line, replacements = process_line(line, new_quotes)
                    replacement_count += replacements
            elif inside_msgstr_block and line.startswith('"'):
                line, replacements = process_line(line, new_quotes)
                replacement_count += replacements
            else:
                inside_msgstr_block = False
            
            updated_lines.append(line)

        with open(file_path, 'w', encoding='utf-8') as file:
            file.writelines(updated_lines)

        message = f"Quotation marks replaced successfully in {replacement_count} pairs." if replacement_count > 0 else "No replacements were made because no suitable \" \" pairs were found."
        print(message)

    except FileNotFoundError:
        print(f"Error: The file at {file_path} was not found.")
    except Exception as e:
        print(f"An error occurred: {e}")

def process_line(line, new_quotes):
    replacements = 0
    # Continue replacing all occurrences of \" in the line
    while '\\"' in line:
        # First replace with opening quote
        line = line.replace('\\"', new_quotes[0], 1)
        replacements += 1  # Increment since we found at least one pair
        if '\\"' in line:  # Check if there's another \" for closing quote
            line = line.replace('\\"', new_quotes[1], 1)
    return line, replacements

# Example usage
if __name__ == '__main__':
    language_code = input("Enter the language code (like zh_CN): ")
    replace_quotation_marks(language_code)

