"""
List ontology structure properties tool for the AGS SPARQL Agent.

This tool lists all properties in a specific ontology structure.
"""

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 list_ontology_structure_properties(ontology_uri: str) -> str:
    """List all properties in a specific ontology.
    
    This tool provides detailed information about properties within a particular
    ontology including type, domain, range, and metadata.
    
    Args:
        ontology_uri: URI of the ontology to explore
        
    Returns:
        JSON response with property list and details
    """
    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 properties in the ontology
    properties_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 ?property ?type ?label ?description ?domain ?range ?superproperty ?created WHERE {{
        GRAPH <{ontology_uri}> {{
            {{
                ?property a owl:ObjectProperty .
                BIND("object" AS ?type)
            }} UNION {{
                ?property a owl:DatatypeProperty .
                BIND("datatype" AS ?type)
            }} UNION {{
                ?property a owl:AnnotationProperty .
                BIND("annotation" AS ?type)
            }}
            OPTIONAL {{ ?property rdfs:label ?label }}
            OPTIONAL {{ ?property dc:description ?description }}
            OPTIONAL {{ ?property rdfs:domain ?domain }}
            OPTIONAL {{ ?property rdfs:range ?range }}
            OPTIONAL {{ ?property rdfs:subPropertyOf ?superproperty }}
            OPTIONAL {{ ?property dct:created ?created }}
        }}
    }}
    ORDER BY ?type ?property
    """
    
    properties_result = agent.anzo_client.query_journal(properties_query)
    properties_table = properties_result.as_table_results().as_list()
    
    # Process property information
    properties_info = []
    property_counts = {"object": 0, "datatype": 0, "annotation": 0}
    
    for prop_row in properties_table:
        property_uri = prop_row[0]
        property_type = prop_row[1] if len(prop_row) > 1 and prop_row[1] else "unknown"
        label = prop_row[2] if len(prop_row) > 2 and prop_row[2] else ""
        description = prop_row[3] if len(prop_row) > 3 and prop_row[3] else ""
        domain = prop_row[4] if len(prop_row) > 4 and prop_row[4] else None
        range_val = prop_row[5] if len(prop_row) > 5 and prop_row[5] else None
        superproperty = prop_row[6] if len(prop_row) > 6 and prop_row[6] else None
        created = prop_row[7] if len(prop_row) > 7 and prop_row[7] else ""
        
        properties_info.append({
            "property_uri": property_uri,
            "property_type": property_type,
            "label": label,
            "description": description,
            "domain_uri": domain,
            "range_uri": range_val,
            "superproperty_uri": superproperty,
            "created": created
        })
        
        if property_type in property_counts:
            property_counts[property_type] += 1
    
    return BaseToolMixin.create_success_response({
        "ontology_uri": ontology_uri,
        "properties": properties_info,
        "property_count": len(properties_info),
        "property_counts_by_type": property_counts
    }, f"Found {len(properties_info)} properties in ontology '{ontology_uri}' ({property_counts['object']} object, {property_counts['datatype']} datatype, {property_counts['annotation']} annotation)")