"""
List transformation steps 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_steps(
    layer_name_or_uri: str,
    graphmart_uri: str = None
) -> str:
    """List all steps in a specific transformation layer.
    
    This tool provides detailed information about all steps
    (both transformation steps and direct load steps) within a specific layer.
    
    Args:
        layer_name_or_uri: Layer name or URI to list steps from
        graphmart_uri: URI of the graphmart (optional, auto-detects)
        
    Returns:
        JSON response with step list and details
    """
    BaseToolMixin.validate_required_param(layer_name_or_uri, "layer_name_or_uri")
    
    # Auto-detect graphmart URI if not provided
    graphmart_uri = get_graphmart_uri(graphmart_uri)
    
    agent = await get_agent()
    
    # Resolve layer URI from name if needed
    layer_uri = None
    layer_title = None
    
    if layer_name_or_uri.startswith("http://"):
        layer_uri = layer_name_or_uri
        # Get layer title
        layer_title_query = f"""
        PREFIX dc: <http://purl.org/dc/elements/1.1/>
        
        SELECT ?title WHERE {{
            GRAPH <{graphmart_uri}> {{
                <{layer_uri}> dc:title ?title .
            }}
        }}
        """
        title_result = agent.anzo_client.query_journal(layer_title_query)
        title_table = title_result.as_table_results().as_list()
        layer_title = title_table[0][0] if title_table and len(title_table) > 0 else "Unknown"
    else:
        # Find layer by name
        layer_lookup_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/>
        
        SELECT ?layer WHERE {{
            GRAPH <{graphmart_uri}> {{
                <{graphmart_uri}> gm:layer ?orderedItem .
                ?orderedItem anzo:orderedValue ?layer .
                ?layer dc:title "{layer_name_or_uri}" .
            }}
        }}
        """
        lookup_result = agent.anzo_client.query_journal(layer_lookup_query)
        table_results = lookup_result.as_table_results().as_list()
        
        if not table_results or len(table_results) == 0:
            raise ToolError(f"Layer '{layer_name_or_uri}' not found in graphmart")
        
        layer_uri = table_results[0][0]
        layer_title = layer_name_or_uri
    
    # Query for all steps in this layer with their metadata
    steps_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 DISTINCT ?step ?stepOrderedItem ?index ?title ?enabled ?created WHERE {{
        GRAPH <{graphmart_uri}> {{
            <{layer_uri}> gm:step ?stepOrderedItem .
            ?stepOrderedItem anzo:orderedValue ?step ;
                            anzo:index ?index .
            ?step dc:title ?title .
            OPTIONAL {{ ?step gm:enabled ?enabled }}
            OPTIONAL {{ ?step dct:created ?created }}
        }}
    }}
    ORDER BY ?index
    """
    
    steps_result = agent.anzo_client.query_journal(steps_query)
    steps_table = steps_result.as_table_results().as_list()
    
    # Process step information
    steps_info = []
    for step_row in steps_table:
        step_uri = step_row[0]
        step_ordered_item_uri = step_row[1]
        index = step_row[2]
        title = step_row[3]
        enabled = step_row[4] if len(step_row) > 4 and step_row[4] else "true"
        created = step_row[5] if len(step_row) > 5 and step_row[5] else ""
        
        # Query step type separately to avoid duplicates
        step_type_query = f"""
        PREFIX gm: <http://cambridgesemantics.com/ontologies/Graphmarts#>
        
        SELECT ?stepType WHERE {{
            GRAPH <{graphmart_uri}> {{
                <{step_uri}> a ?stepType .
            }}
        }}
        """
        
        step_type_result = agent.anzo_client.query_journal(step_type_query)
        step_type_table = step_type_result.as_table_results().as_list()
        
        # Determine step type from results
        step_types = [row[0] for row in step_type_table if row and len(row) > 0]
        step_type_names = [str(t) for t in step_types]
        
        step_type_name = "Unknown"
        if any("DirectLoadStep" in t for t in step_type_names):
            step_type_name = "Direct Load"
        elif any("TransformStep" in t for t in step_type_names):
            step_type_name = "Transform"
        
        steps_info.append({
            "step_uri": step_uri,
            "step_ordered_item_uri": step_ordered_item_uri,
            "index": index,
            "title": title,
            "enabled": enabled,
            "step_type": step_type_name,
            "created": created
        })
    
    return BaseToolMixin.create_success_response({
        "layer_name_or_uri": layer_name_or_uri,
        "resolved_layer_uri": layer_uri,
        "layer_title": layer_title,
        "graphmart_uri": graphmart_uri,
        "total_steps": len(steps_info),
        "steps": steps_info
    }, f"Found {len(steps_info)} steps in layer '{layer_title}'")