import re
import os

# Define template and output file paths
TEMPLATE_FILE = ".env.template"
OUTPUT_FILE = ".env"

def load_template(template_path):
    """
    Load the .env.template file.
    """
    if not os.path.exists(template_path):
        raise FileNotFoundError(f"Template file '{template_path}' not found.")
    
    with open(template_path, 'r') as file:
        return file.readlines()

def parse_variable(line):
    """
    Extract the variable name and default value from a template line.
    """
    match = re.match(r"(.*?)\$\{([^}]+)\}(.*)", line)
    if match:
        prefix, var_value, suffix = match.groups()

        # Extract variable name and default value (if any)
        var_name, default_value = (var_value.split(":-") + [""])[:2]
        return prefix, var_name, default_value, suffix
    return None, None, None, None

def prompt_variable(var_name, default_value):
    """
    Prompt the user to input a value for the variable, using a default if no input is provided.
    """
    user_input = input(f"Enter value for {var_name} [default: {default_value}]: ").strip()
    return user_input if user_input else default_value

def generate_env(template_lines):
    """
    Generate the .env file content by substituting variables from the template.
    """
    output_lines = ["# Generated .env file\n"]
    for line in template_lines:
        # Skip comments and empty lines
        if line.strip().startswith("#") or not line.strip():
            output_lines.append(line)
            continue

        # Parse and process variables
        prefix, var_name, default_value, suffix = parse_variable(line)
        if var_name:
            # Get the default value from the template (already handled in the parsing)
            value = prompt_variable(var_name, default_value)
            output_lines.append(f"{prefix}{value}{suffix}\n")
        else:
            # Unprocessed line (e.g., no variables)
            output_lines.append(line)

    return output_lines

def write_env(output_path, lines):
    """
    Write the generated .env file content to the output file.
    """
    with open(output_path, 'w') as file:
        file.writelines(lines)
    print(f".env file has been successfully created at '{output_path}'.")

def main():
    try:
        # Load the template file
        template_lines = load_template(TEMPLATE_FILE)
        
        # Generate the .env content
        output_lines = generate_env(template_lines)
        
        # Write the content to the .env file
        write_env(OUTPUT_FILE, output_lines)
    
    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    main()
