"""
List Ontology Imports tool for the AGS SPARQL Agent.

This tool handles list ontology imports 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 list_ontology_imports(
    ontology_uri: str
    ) -> str:
    """List all imports for a specific ontology.
    
    This tool shows all owl:imports relationships for an ontology.
    
    Args:
        ontology_uri: URI of the ontology to list imports for (required)
        
    Returns:
        JSON response with import list and details
    """
    BaseToolMixin.validate_required_param(ontology_uri, "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")
    
    # Query for all imports in AGS configuration
    imports_query = f"SELECT ?importedOntology WHERE {{ GRAPH <{ontology_uri}> {{ <{ontology_uri}> <http://www.w3.org/2002/07/owl#imports> ?importedOntology }} }}"
    imports_result = agent.anzo_client.query_journal(imports_query)
    imports_table = imports_result.as_table_results().as_list()
    
    # Process import information
    imports_info = []
    for import_row in imports_table:
        imported_uri = import_row[0]
        
        # Get label and description for the imported ontology
        meta_query = f"""SELECT ?label ?description WHERE {{ 
            GRAPH <{imported_uri}> {{
                OPTIONAL {{ <{imported_uri}> <http://www.w3.org/2000/01/rdf-schema#label> ?label }} 
                OPTIONAL {{ <{imported_uri}> <http://purl.org/dc/elements/1.1/description> ?description }} 
            }}
        }}"""
        meta_result = agent.anzo_client.query_journal(meta_query)
        meta_table = meta_result.as_table_results().as_list()
        
        label = ""
        description = ""
        if meta_table and len(meta_table) > 0:
            if len(meta_table[0]) > 0 and meta_table[0][0]:
                label = meta_table[0][0]
            if len(meta_table[0]) > 1 and meta_table[0][1]:
                description = meta_table[0][1]
        
        imports_info.append({
            "imported_ontology_uri": imported_uri,
            "label": label,
            "description": description
        })
    
    return BaseToolMixin.create_success_response({
        "ontology_uri": ontology_uri,
        "imports": imports_info,
        "import_count": len(imports_info)
    }, f"Found {len(imports_info)} imports for ontology '{ontology_uri}'")