"""
List transformation layers tool for the AGS SPARQL Agent.
"""

import os
import sys

# Add src directory to path for imports
src_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
if src_dir not in sys.path:
    sys.path.insert(0, src_dir)

from ..base_tool import BaseToolMixin, handle_tool_errors, ToolError
from ...utils.agent_utils import get_graphmart_uri, get_rest_api_client


@handle_tool_errors
async def list_transformation_layers(graphmart_uri: str = None) -> str:
    """List all transformation layers with their steps.
    
    This tool provides an overview of all transformation layers
    in the graphmart with their step counts and metadata.
    
    Args:
        graphmart_uri: URI of the graphmart (optional, auto-detects)
        
    Returns:
        JSON response with layer list and details
    """
    # Auto-detect graphmart URI if not provided
    graphmart_uri = get_graphmart_uri(graphmart_uri)
    
    # Retrieve layers via REST API
    api = get_rest_api_client()
    layers = api.retrieve_graphmart_layers(graphmart_uri)
    
    # Build layer info list, counting steps per layer via API
    layers_info = []
    for idx, layer in enumerate(layers):
        layer_uri = str(layer.uri) if hasattr(layer, 'uri') else str(layer)
        title = getattr(layer, 'title', '')
        description = getattr(layer, 'description', '')
        enabled = getattr(layer, 'enabled', True)
        created = getattr(layer, 'created', '')
        
        # Count steps via REST API
        try:
            steps = api.retrieve_layer_steps(layer_uri)
            step_count = len(steps)
        except Exception:
            step_count = 0
        
        layers_info.append({
            "layer_uri": layer_uri,
            "layer_ordered_item_uri": "",
            "index": str(idx),
            "title": title,
            "description": description or "",
            "enabled": str(enabled).lower() if isinstance(enabled, bool) else str(enabled),
            "created": str(created) if created else "",
            "step_count": step_count
        })
    
    return BaseToolMixin.create_success_response({
        "graphmart_uri": graphmart_uri,
        "total_layers": len(layers_info),
        "layers": layers_info
    }, f"Found {len(layers_info)} transformation layers in graphmart")