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

    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-6): ")) - 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
        quote_open = False  # To keep track if we are inside a quote block

        for line in lines:
            if line.startswith('msgstr'):
                inside_msgstr_block = True
                if not line.strip() == 'msgstr ""':
                    line, replacements, quote_open = process_line(line, new_quotes, quote_open)
                    replacement_count += replacements
            elif inside_msgstr_block and line.startswith('"'):
                line, replacements, quote_open = process_line(line, new_quotes, quote_open)
                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, quote_open):
    replacements = 0

    # Continue replacing all occurrences of \" in the line
    while '\\"' in line:
        if not quote_open:  # If quote is not open, replace opening quote
            line = line.replace('\\"', new_quotes[0], 1)
            quote_open = True
        else:  # If quote is open, replace closing quote
            line = line.replace('\\"', new_quotes[1], 1)
            quote_open = False
            replacements += 1

    return line, replacements, quote_open

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