"""
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_agent, get_graphmart_uri


@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)
    
    agent = await get_agent()
    
    # Query for all layers with their metadata
    layers_query = f"""
    PREFIX gm: <http://cambridgesemantics.com/ontologies/Graphmarts#>
    PREFIX anzo: <http://openanzo.org/ontologies/2008/07/Anzo#>
    PREFIX dc: <http://purl.org/dc/elements/1.1/>
    PREFIX dct: <http://purl.org/dc/terms/>
    
    SELECT ?layer ?layerOrderedItem ?index ?title ?description ?enabled ?created WHERE {{
        GRAPH <{graphmart_uri}> {{
            <{graphmart_uri}> gm:layer ?layerOrderedItem .
            ?layerOrderedItem anzo:orderedValue ?layer ;
                             anzo:index ?index .
            ?layer dc:title ?title .
            OPTIONAL {{ ?layer dc:description ?description }}
            OPTIONAL {{ ?layer gm:enabled ?enabled }}
            OPTIONAL {{ ?layer dct:created ?created }}
        }}
    }}
    ORDER BY ?index
    """
    
    layers_result = agent.anzo_client.query_journal(layers_query)
    layers_table = layers_result.as_table_results().as_list()
    
    # For each layer, count its steps
    layers_info = []
    for layer_row in layers_table:
        layer_uri = layer_row[0]
        layer_ordered_item_uri = layer_row[1]
        index = layer_row[2]
        title = layer_row[3]
        description = layer_row[4] if len(layer_row) > 4 and layer_row[4] else ""
        enabled = layer_row[5] if len(layer_row) > 5 and layer_row[5] else "true"
        created = layer_row[6] if len(layer_row) > 6 and layer_row[6] else ""
        
        # Count steps in this layer
        steps_count_query = f"""
        PREFIX gm: <http://cambridgesemantics.com/ontologies/Graphmarts#>
        PREFIX anzo: <http://openanzo.org/ontologies/2008/07/Anzo#>
        
        SELECT (COUNT(?step) AS ?stepCount) WHERE {{
            GRAPH <{graphmart_uri}> {{
                <{layer_uri}> gm:step ?stepOrderedItem .
                ?stepOrderedItem anzo:orderedValue ?step .
            }}
        }}
        """
        
        steps_count_result = agent.anzo_client.query_journal(steps_count_query)
        steps_count_table = steps_count_result.as_table_results().as_list()
        step_count = 0
        if steps_count_table and len(steps_count_table) > 0 and steps_count_table[0]:
            try:
                step_count = int(steps_count_table[0][0])
            except (ValueError, TypeError):
                step_count = 0
        
        layers_info.append({
            "layer_uri": layer_uri,
            "layer_ordered_item_uri": layer_ordered_item_uri,
            "index": index,
            "title": title,
            "description": description,
            "enabled": enabled,
            "created": created,
            "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")