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

"""
CapabilityCombiner: A meta-capability that combines existing Python capabilities into new ones by generating and saving Python code programmatically.

This module provides a framework for creating new Python tools by combining existing capabilities. It allows you to add multiple capabilities, merge them into a single Python script, and save the result to a file.

Example usage:
    combiner = CapabilityCombiner()
    combiner.add_capability(cap1_code, "Capability One", author="John Doe", version="0.1")
    combiner.add_capability(cap2_code, "Capability Two", author="Jane Smith", version="0.2")
    combiner.write_to_file("combined_capability.py")

The generated code will include all capabilities combined into a single module with proper imports and documentation.
"""

class CapabilityCombiner:
    def __init__(self):
        """Initialize the CapabilityCombiner with empty lists for storing capabilities and metadata."""
        self.capabilities = []  # List to store individual capabilities
        self.metadata = {}     # Dictionary to store overall module metadata

    def add_capability(self, code, name, **kwargs):
        """
        Add a new capability to be combined.
        
        Args:
            code (str): The Python code of the capability
            name (str): Name of the capability
            **kwargs: Additional metadata such as author, version, description
            
        Returns:
            None
        """
        capability = {
            'code': code,
            'name': name,
            'metadata': kwargs
        }
        self.capabilities.append(capability)
        
    def _consolidate_imports(self):
        """
        Consolidate imports from all capabilities to avoid duplicates.
        
        Returns:
            str: A string containing consolidated import statements
        """
        imports = set()
        for capability in self.capabilities:
            lines = capability['code'].split('\n')
            for line in lines:
                if line.startswith('import ') and not line.startswith('import sys'):
                    parts = line.strip().split()
                    if len(parts) >= 2:
                        module = parts[1].rstrip(',')
                        imports.add(module)
        return '\n'.join([f'import {imp}' for imp in sorted(imports)])
        
    def _generate_docstring(self):
        """
        Generate a comprehensive docstring for the combined capability.
        
        Returns:
            str: A formatted docstring with all capabilities and metadata
        """
        doc_lines = []
        # Add general module description
        doc_lines.append(f"Combined capability containing {len(self.capabilities)} sub-capabilities.")
        if self.metadata.get('description'):
            doc_lines.append(f"\nDescription:\n{self.metadata['description']}")
        else:
            doc_lines.append("\nNo detailed description provided.")
            
        # Add each capability's metadata
        for cap in self.capabilities:
            lines = []
            lines.append(f"")
            lines.append(f"Capability: {cap['name']}")
            meta = cap['metadata']
            if meta.get('author'):
                lines.append(f"Author: {meta['author']}")
            if meta.get('version'):
                lines.append(f"Version: {meta['version']}")
            if meta.get('description'):
                lines.append(f"Description:\n{meta['description']}")
            doc_lines.extend(lines)
        return '\n'.join(doc_lines)

    def merge_capabilities(self):
        """
        Combine all capabilities into a single string of Python code.
        
        Returns:
            str: The combined Python code as a string
        """
        # Start with imports
        import_section = self._consolidate_imports()
        
        # Add metadata and docstring
        docstring = f'''"""
{_generate_docstring()}
"""'''
        
        # Combine all capability code into the body of the module
        combined_code = []
        for cap in self.capabilities:
            lines = cap['code'].split('\n')
            for line in lines:
                if not line.startswith('import '):
                    combined_code.append(line)
                    
        # Assemble everything
        full_code = f'''{import_section}
{docstring}

# Combined capability code
{chr(10).join(combined_code)}'''
        
        return full_code

    def write_to_file(self, filename=None, directory='.'):
        """
        Write the combined capability to a Python file.
        
        Args:
            filename (str, optional): Name of the output file. Defaults to "combined_capability.py".
            directory (str, optional): Directory where to save the file. Defaults to current directory.
            
        Returns:
            None
            
        Raises:
            FileNotFoundError: If the specified directory does not exist
        """
        # Set default filename if none provided
        if not filename:
            filename = "combined_capability.py"
            
        # Ensure the directory exists
        import os
        if not os.path.exists(directory):
            raise FileNotFoundError(f"Directory '{directory}' does not exist.")
            
        # Generate the code
        combined_code = self.merge_capabilities()
        
        # Write to file
        filepath = os.path.join(directory, filename)
        with open(filepath, 'w') as f:
            f.write(combined_code)
        print(f"Successfully wrote combined capability to {filepath}")
