"""
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_graphmart_uri, get_rest_api_client


@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)
    
    api = get_rest_api_client()
    
    # Resolve layer URI from name if needed
    layer_uri = None
    layer_title = None
    
    if layer_name_or_uri.startswith("http://") or layer_name_or_uri.startswith("https://"):
        layer_uri = layer_name_or_uri
        # Get layer title via API
        try:
            layer_obj = api.retrieve_layer(layer_uri)
            layer_title = getattr(layer_obj, 'title', 'Unknown') if layer_obj else 'Unknown'
        except Exception:
            layer_title = "Unknown"
    else:
        # Find layer by name using API
        layers = api.retrieve_graphmart_layers(graphmart_uri)
        for l in layers:
            if getattr(l, 'title', '') == layer_name_or_uri:
                layer_uri = str(l.uri) if hasattr(l, 'uri') else str(l)
                layer_title = layer_name_or_uri
                break
        
        if not layer_uri:
            raise ToolError(f"Layer '{layer_name_or_uri}' not found in graphmart")
    
    # Retrieve steps via REST API
    steps = api.retrieve_layer_steps(layer_uri)
    
    # Process step information
    steps_info = []
    for idx, step in enumerate(steps):
        step_uri = str(step.uri) if hasattr(step, 'uri') else str(step)
        title = getattr(step, 'title', '')
        enabled = getattr(step, 'enabled', True)
        created = getattr(step, 'created', '')
        step_type_raw = getattr(step, 'step_type', getattr(step, 'type', 'Unknown'))
        
        # Map step type to friendly name
        step_type_name = "Unknown"
        step_type_str = str(step_type_raw)
        if "DirectLoad" in step_type_str:
            step_type_name = "Direct Load"
        elif "Query" in step_type_str or "Transform" in step_type_str:
            step_type_name = "Transform"
        
        steps_info.append({
            "step_uri": step_uri,
            "step_ordered_item_uri": "",
            "index": str(idx),
            "title": title,
            "enabled": str(enabled).lower() if isinstance(enabled, bool) else str(enabled),
            "step_type": step_type_name,
            "created": str(created) if created else ""
        })
    
    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}'")