"""
Execute SPARQL query tool for the AGS SPARQL Agent.

This tool executes SPARQL queries directly against the graphmart.
"""

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


@handle_tool_errors
async def execute_sparql_query(sparql: str, explain: bool = False) -> str:
    """Execute SPARQL queries directly against the graphmart.
    
    This tool executes SPARQL SELECT, INSERT, UPDATE, or DELETE queries
    directly against the target graphmart with optional query explanation.
    
    Args:
        sparql: SPARQL query to execute (required)
        explain: Whether to explain the SPARQL query execution
        
    Returns:
        JSON response with query results and execution statistics
    """
    BaseToolMixin.validate_required_param(sparql, "sparql")
    
    agent = await get_agent()
    
    # Execute the provided SPARQL directly using the agent's method
    result = await agent.query_sparql_direct(sparql=sparql, question=None, explain=explain)
    
    return BaseToolMixin.create_success_response({
        "data": result.data,
        "sparql_query": result.sparql_query,
        "execution_time": result.execution_time or 0.0,
        "column_names": result.column_names or [],
        "query_successful": result.success
    }) if result.success else BaseToolMixin.create_error_response(
        result.error_message or "Query execution failed",
        details={
            "sparql_query": sparql,
            "execution_time": result.execution_time or 0.0
        }
    )