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

"""
CapabilityCombiner.py

This module provides a framework for combining multiple Python capabilities into a single script.
It allows users to merge functionality from different modules or packages into a unified codebase,
saving the combined result as a new Python file. The tool supports both code generation and file manipulation.

The system consists of:
- A main capability combiner class that handles code merging
- Example capabilities in the 'capabilities' directory
- Functions for reading, writing, and combining code snippets

Example Usage:
    1. Create or add capability modules in the 'capabilities' folder.
    2. Use CapabilityCombiner to merge desired capabilities into a single script.
    3. Save and execute the generated script.

Documentation:
    - combine_capabilities(): Generates combined Python scripts from multiple sources
    - save_generated_script(): Writes merged code to file
    - load_capability(): Reads individual capability modules
"""

import os
from importlib.machinery import SourceFileLoader


class CapabilityCombiner:
    """
    A class for combining multiple Python capabilities into a single script.

    Attributes:
        combined_code (str): Storage for the generated combined code.
        capabilities_dir (str): Directory where capabilities are stored.
    """

    def __init__(self, capabilities_path="capabilities"):
        self.combined_code = ""
        self.capabilities_dir = capabilities_path

    def load_capability(self, module_name):
        """
        Load and import a capability module.

        Args:
            module_name (str): Name of the module to import.

        Returns:
            object: The imported module.
        """
        try:
            module_path = os.path.join(self.capabilities_dir, f"{module_name}.py")
            loader = SourceFileLoader(module_name, module_path)
            module = loader.load_module()
            return module
        except Exception as e:
            raise ImportError(f"Failed to import {module_name}: {e}")

    def combine_capabilities(self, *capability_names):
        """
        Combine multiple capabilities into a single code string.

        Args:
            *capability_names (str): Variable number of capability names to combine.

        Returns:
            str: Combined Python code.
        """
        combined = []
        for cap in capability_names:
            module = self.load_capability(cap)
            if hasattr(module, "__all__"):
                functions_to_include = getattr(module, "__all__")
                for func in functions_to_include:
                    combined.append(f"from {cap} import {func}")
            else:
                combined.append(f"import {cap}")
        return "\n".join(combined)

    def save_generated_script(self, script_name="combined_script.py"):
        """
        Save the generated code to a file.

        Args:
            script_name (str): Name of the output script. Defaults to "combined_script.py".
        """
        with open(script_name, "w", encoding="utf-8") as f:
            f.write(self.combined_code)
        print(f"Script saved as {script_name}")

    def __repr__(self):
        return f"CapabilityCombiner(capabilities_dir={self.capabilities_dir})"


def main():
    """
    Main function to demonstrate using CapabilityCombiner.
    Combines example capabilities and executes the generated script.
    """
    combiner = CapabilityCombiner()
    
    print("Combining capabilities...")
    combined_code = combiner.combine_capabilities(
        "math_operations",
        "string_manipulation"
    )
    
    print("\nGenerated Code:")
    print(combined_code)
    
    combiner.save_generated_script()
    
    # For demonstration, execute the generated script
    print("\nExecuting generated script...")
    import subprocess
    try:
        subprocess.run([os.path.join(os.getcwd(), "combined_script.py")], shell=True)
    except FileNotFoundError as e:
        print(f"Error executing script: {e}")

if __name__ == "__main__":
    main()
