"""
Core integration layer between Ape and ape-langchain.

Provides thin wrappers around ape.compile and ape.validate
to maintain API stability even as Ape core evolves.
"""

from typing import Any
from pathlib import Path

# Import from ape core
try:
    from ape import compile as ape_compile
    from ape import validate as ape_validate
    from ape import ApeModule
    from ape import ApeCompileError, ApeValidationError, ApeExecutionError
except ImportError as e:
    raise ImportError(
        "ape-langchain requires ape-lang to be installed. "
        "Install it with: pip install ape-lang"
    ) from e


def compile_ape(source_or_path: str | Path) -> ApeModule:
    """
    Compile Ape source code or file to an executable module.
    
    This is a thin wrapper around ape.compile() that provides
    API stability for ape-langchain.
    
    Args:
        source_or_path: Path to .ape file or raw Ape source code
        
    Returns:
        ApeModule: Compiled module ready for execution
        
    Raises:
        ApeCompileError: If compilation fails
    """
    return ape_compile(source_or_path)


def validate_ape(module: ApeModule) -> None:
    """
    Validate an Ape module for semantic correctness.
    
    This is a thin wrapper around ape.validate() that provides
    API stability for ape-langchain.
    
    Args:
        module: The compiled ApeModule to validate
        
    Raises:
        ApeValidationError: If validation fails
    """
    ape_validate(module)


def execute_ape_function(module: ApeModule, function_name: str, **kwargs) -> Any:
    """
    Execute a function from a compiled Ape module.
    
    This standardizes function execution across ape-langchain,
    providing a stable API even if the underlying Ape runtime evolves.
    
    Args:
        module: Compiled ApeModule
        function_name: Name of the function to call
        **kwargs: Arguments to pass to the function
        
    Returns:
        The function's return value
        
    Raises:
        ApeExecutionError: If execution fails
        AttributeError: If function doesn't exist
        TypeError: If arguments are invalid
    """
    try:
        # Use the ApeModule.call() method from Ape core
        return module.call(function_name, **kwargs)
    except AttributeError:
        # Function doesn't exist - re-raise with helpful message
        available = ", ".join(module.list_functions())
        raise AttributeError(
            f"Function '{function_name}' not found in module. "
            f"Available functions: {available}"
        )
    except Exception as e:
        # Wrap other execution errors
        raise ApeExecutionError(f"Execution of '{function_name}' failed: {e}") from e


__all__ = [
    "compile_ape",
    "validate_ape",
    "execute_ape_function",
    "ApeModule",
    "ApeCompileError",
    "ApeValidationError", 
    "ApeExecutionError",
]
