"""
META-CAPABILITY: meta_unnamed
Code that creates code!
"""

"""
This module provides a template engine capable of generating Python code.

The TemplateEngine class allows users to register code templates and generate new
Python files from those templates. Templates are defined using placeholders that will
be replaced with user-provided values when generating code.

Example usage:
    engine = TemplateEngine()
    engine.register_template("hello-world", "def greet(name):\\n    print(f'Hello, {name}!')\\n")
    generated_code = engine.generate_code(template_name="hello-world", data={"name": "World"})
    engine.save_to_file(generated_code, file_path="generated.py")
"""

class TemplateEngine:
    """
    A template engine that generates Python code from registered templates.

    Attributes:
        templates (dict): Stores registered templates with their names as keys
                        and the template strings as values.
    """

    def __init__(self):
        self.templates = {}

    def register_template(self, name: str, template: str) -> None:
        """
        Registers a new template with the engine.

        Args:
            name (str): The name of the template.
            template (str): The Python code template to register.

        Raises:
            ValueError: If a template with the same name already exists.
        """
        if name in self.templates:
            raise ValueError(f"Template '{name}' already registered.")
        self.templates[name] = template

    def generate_code(self, template_name: str, data: dict) -> str:
        """
        Generates Python code by filling in placeholders in a registered template.

        Args:
            template_name (str): The name of the template to use.
            data (dict): Dictionary containing values to replace placeholders.

        Returns:
            str: Generated Python code as a string.

        Raises:
            KeyError: If the template is not found or required keys are missing.
            ValueError: If no templates are registered.
        """
        if not self.templates:
            raise ValueError("No templates have been registered.")

        if template_name not in self.templates:
            raise KeyError(f"Template '{template_name}' not found.")

        try:
            template = self.templates[template_name]
            code = template.format(**data)
            return code
        except KeyError as e:
            raise KeyError(f"Missing data key: {e}")

    def save_to_file(self, code: str, file_path: str) -> None:
        """
        Saves generated Python code to a file.

        Args:
            code (str): The generated Python code.
            file_path (str): Path where the code should be saved.

        Raises:
            OSError: If there are issues saving the file.
        """
        with open(file_path, "w") as f:
            f.write(code)

    def list_templates(self) -> list:
        """
        Returns a list of registered template names.

        Returns:
            list: List of template names.
        """
        return list(self.templates.keys())

if __name__ == "__main__":
    import sys
    from pathlib import Path

    def main():
        engine = TemplateEngine()

        # Example templates
        example_templates = {
            "hello-world": "def greet(name):\\n    print(f'Hello, {name}!')",
            "math-add": "def add(a, b):\\n    return a + b"
        }

        for name, template in example_templates.items():
            engine.register_template(name, template)

        # Generate and save code
        try:
            template_name = input("Enter template name: ")
            data_input = input("Enter replacement values (comma-separated key=value pairs): ").split(',')
            data = {}
            for pair in data_input:
                if '=' in pair:
                    key, value = pair.split('=', 1)
                    data[key] = value.strip()

            code = engine.generate_code(template_name, data)
            output_path = input("Enter output file path: ")
            engine.save_to_file(code, output_path)
            print(f"Generated code saved to {output_path}")
        except Exception as e:
            print(f"Error: {str(e)}")
            sys.exit(1)

    main()
