"""
List Ontology Structure Classes tool for the AGS SPARQL Agent.

This tool handles list ontology structure classes 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


@handle_tool_errors
async def list_ontology_structure_classes(ontology_uri: str) -> str:
    """List all classes defined in a specific ontology schema.
    
    This tool provides detailed information about all classes within an ontology's
    structure, regardless of whether they have instances. Use this to explore
    the complete ontology schema and class definitions.
    
    Args:
        ontology_uri: URI of the ontology to explore
        
    Returns:
        JSON response with complete class schema including labels, descriptions, and hierarchy
    """
    BaseToolMixin.validate_required_param(ontology_uri, "ontology_uri")
    BaseToolMixin.validate_uri(ontology_uri, "ontology_uri")
    
    agent = await get_agent()
    
    # Check if ontology exists
    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 classes in the ontology
    classes_query = f"""
    PREFIX owl: <http://www.w3.org/2002/07/owl#>
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    PREFIX dc: <http://purl.org/dc/elements/1.1/>
    PREFIX dct: <http://purl.org/dc/terms/>
    
    SELECT ?class ?label ?description ?superclass ?created WHERE {{
        GRAPH <{ontology_uri}> {{
            ?class a owl:Class .
            OPTIONAL {{ ?class rdfs:label ?label }}
            OPTIONAL {{ ?class dc:description ?description }}
            OPTIONAL {{ ?class rdfs:subClassOf ?superclass }}
            OPTIONAL {{ ?class dct:created ?created }}
        }}
    }}
    ORDER BY ?class
    """
    
    classes_result = agent.anzo_client.query_journal(classes_query)
    classes_table = classes_result.as_table_results().as_list()
    
    # Process class information
    classes_info = []
    for class_row in classes_table:
        class_uri = class_row[0]
        label = class_row[1] if len(class_row) > 1 and class_row[1] else ""
        description = class_row[2] if len(class_row) > 2 and class_row[2] else ""
        superclass = class_row[3] if len(class_row) > 3 and class_row[3] else None
        created = class_row[4] if len(class_row) > 4 and class_row[4] else ""
        
        classes_info.append({
            "class_uri": class_uri,
            "label": label,
            "description": description,
            "superclass_uri": superclass,
            "created": created
        })
    
    return BaseToolMixin.create_success_response({
        "ontology_uri": ontology_uri,
        "classes": classes_info,
        "class_count": len(classes_info)
    }, f"Found {len(classes_info)} classes in ontology '{ontology_uri}'")