import json
import math
import os

lang = "en_us.json"  # Change this to your language

def split_text(count, string):
    step = len(string) / count
    revealed_strings = []
    for i in range(count):
        cur = int(math.ceil(step * (i + 1)))
        revealed_strings.append(string[:cur])
    return revealed_strings

def gradual_reveal(strings, repeat_counts, keys, prefix="bungeon.dialogue."):
    updated_data = {}  # To store updated values during the reveal
    for idx, (string, repeat_count) in enumerate(zip(strings, repeat_counts)):
        revealed_steps = split_text(repeat_count, string)
        for i, revealed in enumerate(revealed_steps[:-1]):  # Exclude the last iteration
            updated_data[prefix + keys[idx] + f"_{i}"] = revealed
    return updated_data

def append_to_json(file_path, updated_data):
    with open(file_path, 'r') as file:
        original_content = file.read()

    json_end_index = original_content.rfind("}")
    formatted_data = json.dumps(updated_data, indent=4)[1:-1]  # Remove outer braces

    # Fix indentation: Replace 4 spaces with a single tab
    formatted_data = formatted_data.replace("    ", "\t")

    # Remove trailing whitespace from the original content
    original_content = original_content[:json_end_index].rstrip()

    # Add two newlines between the user-made content and the generated content
    updated_content = (
        original_content +  # Existing content without trailing whitespace
        ",\n\n" +  # Add a comma and two newlines
        formatted_data + "\n}"  # Add the formatted data and the closing brace
    )

    with open(file_path, 'w') as file:
        file.write(updated_content)

def main():
    # Get the directory where the script is located
    script_dir = os.path.dirname(os.path.abspath(__file__))

    # Navigate to the parent folder
    parent_dir = os.path.dirname(script_dir)

    # Define the path to the language file
    lang_file = os.path.join(parent_dir, lang)

    # Load the language file
    with open(lang_file, "r") as file:
        data = json.load(file)
    
    # Define input keys and repeat counts
    repeat_counts = [27, 15, 25, 24, 10, 25, 32, 42, 18, 20, 27, 38, 38]
    input_keys = [
        "scientist.hub.0",
        "scientist.hub.1",
        "scientist.hub.2",
        "scientist.hub.3",
        "scientist.hub.4",
        "scientist.trial.0",
        "scientist.trial.1",
        "scientist.trial.2",
        "scientist.victory.0",
        "scientist.victory.1",
        "scientist.victory.2",
        "scientist.victory.3",
        "scientist.victory.4"
    ]
    input_strings = [data.get("bungeon.dialogue." + key, "") for key in input_keys]

    # Generate updated data
    updated_data = gradual_reveal(input_strings, repeat_counts, input_keys)

    # Append updated data to the language file
    append_to_json(lang_file, updated_data)

if __name__ == "__main__":
    main()
    print("Filled dialogue in", lang)