"""
Create transformation layer tool for the AGS SPARQL Agent.

Uses REST API (identical in v5.4 and v6.2) instead of journal writes.
"""

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


@handle_tool_errors
async def create_transformation_layer(
    layer_name: str,
    layer_description: str,
    graphmart_uri: str = None,
    order_after: str = None,
    explanation: str = None,
    dry_run: bool = False
) -> str:
    """Create a new transformation layer in the specified graphmart.
    
    This tool creates a new transformation layer with proper ordering and
    metadata for organizing data transformation steps.
    
    Args:
        layer_name: Human-readable name for the layer (e.g., "ERP Linking")
        layer_description: Description of what this layer does
        graphmart_uri: URI of the graphmart (optional, auto-detects)
        order_after: Layer name to put this layer after (optional, defaults to end)
        explanation: Human-readable description of the operation (required)
        dry_run: If true, validate inputs without executing
        
    Returns:
        JSON response with layer creation results
    """
    BaseToolMixin.validate_required_param(layer_name, "layer_name")
    BaseToolMixin.validate_required_param(layer_description, "layer_description")
    BaseToolMixin.validate_required_param(explanation, "explanation")
    
    # Auto-detect graphmart URI if not provided
    graphmart_uri = get_graphmart_uri(graphmart_uri)
    
    # Dry run mode
    if dry_run:
        return BaseToolMixin.create_success_response({
            "dry_run": True,
            "layer_name": layer_name,
            "graphmart_uri": graphmart_uri,
            "explanation": explanation
        }, "Layer creation validated. Set dry_run=false to execute.")
    
    # Create layer via REST API (handles ordering, metadata, URIs automatically)
    api = get_rest_api_client()
    layer = api.create_graphmart_layer(
        graphmart_uri,
        title=layer_name,
        description=layer_description,
        enabled=True,
        visible=True,
        exposed=True,
        defaultSelected=True,
        canExclude=True,
    )
    
    return BaseToolMixin.create_success_response({
        "layer_name": layer_name,
        "layer_uri": layer.uri if hasattr(layer, 'uri') else str(layer),
        "graphmart_uri": graphmart_uri,
        "explanation": explanation
    }, f"Successfully created transformation layer '{layer_name}'")