"""
Add Ontology Import tool for the AGS SPARQL Agent.

This tool handles add ontology import operations.
"""

import os
import sys
from datetime import datetime

# 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


async def add_ontology_import(
    ontology_uri: str,
    imported_ontology_uri: str,
    explanation: str = None,
    dry_run: bool = False
    ) -> str:
    """Add an import statement to an ontology.
    
    This tool adds an owl:imports relationship between ontologies,
    allowing the importing ontology to use classes and properties
    from the imported ontology.
    
    Args:
        ontology_uri: URI of the ontology to add import to (required)
        imported_ontology_uri: URI of the ontology to import (required)
        explanation: Human-readable description of the operation
        dry_run: If true, validate inputs without executing
        
    Returns:
        JSON response with import addition results
    """
    BaseToolMixin.validate_required_param(ontology_uri, "ontology_uri")
    BaseToolMixin.validate_required_param(imported_ontology_uri, "imported_ontology_uri")
    
    agent = await get_agent()
    
    # Check if ontology exists in AGS configuration
    exists_query = f"SELECT ?o WHERE {{ GRAPH <{ontology_uri}> {{ <{ontology_uri}> a ?o }} }}"
    exists_result = agent.anzo_client.query_journal(exists_query)
    table_results = exists_result.as_table_results().as_list()
    ontology_exists = len(table_results) > 0
    
    if not ontology_exists:
        raise ToolError(f"Ontology '{ontology_uri}' not found")
    
    # Check if import already exists in AGS configuration
    import_exists_query = f"SELECT ?importedOntology WHERE {{ GRAPH <{ontology_uri}> {{ <{ontology_uri}> <http://www.w3.org/2002/07/owl#imports> ?importedOntology . FILTER(?importedOntology = <{imported_ontology_uri}>) }} }}"
    import_exists_result = agent.anzo_client.query_journal(import_exists_query)
    table_results = import_exists_result.as_table_results().as_list()
    import_already_exists = len(table_results) > 0
    
    if import_already_exists:
        return BaseToolMixin.create_success_response({
            "ontology_uri": ontology_uri,
            "imported_ontology_uri": imported_ontology_uri,
            "already_exists": True,
            "explanation": explanation
        }, f"Import relationship already exists between '{ontology_uri}' and '{imported_ontology_uri}'")
    
    # Dry run mode
    if dry_run:
        return BaseToolMixin.create_success_response({
            "dry_run": True,
            "ontology_uri": ontology_uri,
            "imported_ontology_uri": imported_ontology_uri,
            "explanation": explanation
        }, "Import addition validated. Set dry_run=false to execute.")
    
    # Get current timestamp for metadata
    current_timestamp = datetime.now().strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'
    
    # Add the import statement to AGS configuration
    add_import_sparql = f"""
    PREFIX owl: <http://www.w3.org/2002/07/owl#>
    PREFIX dct: <http://purl.org/dc/terms/>
    
    INSERT DATA {{
        GRAPH <{ontology_uri}> {{
            <{ontology_uri}> owl:imports <{imported_ontology_uri}> ;
                            dct:modified "{current_timestamp}" ;
                            dct:modifier <http://openanzo.org/system/internal/sysadmin> .
        }}
    }}
    """
    
    # Execute the import addition in AGS configuration
    agent.anzo_client.update_journal(add_import_sparql)
    
    return BaseToolMixin.create_success_response({
        "ontology_uri": ontology_uri,
        "imported_ontology_uri": imported_ontology_uri,
        "added_timestamp": current_timestamp,
        "explanation": explanation
    }, f"Successfully added import of '{imported_ontology_uri}' to '{ontology_uri}'")