import os
import random
import pystache
import argparse
import re

def render_templates(template_dir, project_name):
    import pystache  # Import after ensuring it's installed

    # Generate a random port number
    port = random.randint(8900, 9400)

    # Mustache data (dynamic placeholders)
    data = {
        "PROJECT_NAME": str(project_name).lower(),
        "PORT": port
    }

    # Define a regex for detecting [[ ... ]] custom placeholders
    pattern = re.compile(r"\[\[(.*?)\]\]")

    # Process all .tmpl files in the directory
    for root, _, files in os.walk(template_dir):
        for file in files:
            if file.endswith(".tmpl"):
                tmpl_file = os.path.join(root, file)
                output_file = os.path.join(root, file.replace(".tmpl", ""))

                # Read the template file
                with open(tmpl_file, 'r') as f:
                    template_content = f.read()

                # Replace placeholders wrapped with [[ ... ]]
                def replace_placeholder(match):
                    key = match.group(1)
                    return str(data.get(key, match.group(0)))  # Replace only if key exists

                rendered_content = pattern.sub(replace_placeholder, template_content)

                # Write to output file
                with open(output_file, 'w') as f:
                    f.write(rendered_content)
                print(f"Generated: {output_file}")


def main():
    # Parse arguments
    parser = argparse.ArgumentParser(description="Render Mustache templates in a directory.")
    parser.add_argument('--project-name', type=str, help='Project name (defaults to current directory name)')
    parser.add_argument('--template-dir', type=str, default='.gitea/workflows', help='Template directory')
    args = parser.parse_args()

    # Get the project name (current directory name if not provided)
    project_name = args.project_name or os.path.basename(os.getcwd())

    # Render templates
    render_templates(args.template_dir, project_name)

if __name__ == "__main__":
    main()

