"""
Ontology discovery tool for the AGS SPARQL Agent.

This tool discovers and profiles all ontologies with their class and
property counts for quick overview of available knowledge domains.
"""

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 discover_available_ontologies() -> str:
    """Discover all ontologies available in the current graphmart.
    
    This tool discovers and profiles all ontologies with their class and
    property counts for quick overview of available knowledge domains.
    
    Returns:
        JSON response with ontology list and statistics
    """
    agent = await get_agent()
    
    # Ensure ontology info is available
    if not agent.ontology_info:
        await agent._discover_ontologies()
    
    # Get actual ontology URIs discovered by the ontology manager
    # instead of inferring from class/property naming patterns
    ontology_refs = await agent.ontology_manager._discover_ontology_references()
    
    # Extract unique ontology URIs from the discovery results
    discovered_ontology_uris = set()
    for source_property, ontology_uri in ontology_refs:
        discovered_ontology_uris.add(ontology_uri)
    
    # Build ontology list using discovered URIs with counts from loaded data
    ontologies = []
    for ontology_uri in sorted(discovered_ontology_uris):
        # Count classes in this ontology by querying the ontology graph directly
        try:
            class_count_query = f"""
            SELECT (COUNT(DISTINCT ?class) AS ?count) WHERE {{
                GRAPH <{ontology_uri}> {{
                    ?class a ?classType .
                    FILTER(?classType IN (
                        <http://www.w3.org/2000/01/rdf-schema#Class>, 
                        <http://www.w3.org/2002/07/owl#Class>
                    ))
                }}
            }}
            """
            class_result = agent.anzo_client.query_journal(class_count_query)
            class_table = class_result.as_table_results().as_list()
            class_count = int(class_table[0][0]) if class_table and class_table[0] and class_table[0][0] else 0
        except Exception:
            class_count = 0
        
        # Count properties in this ontology by querying the ontology graph directly
        try:
            prop_count_query = f"""
            SELECT (COUNT(DISTINCT ?property) AS ?count) WHERE {{
                GRAPH <{ontology_uri}> {{
                    ?property a ?propType .
                    FILTER(?propType IN (
                        <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property>,
                        <http://www.w3.org/2002/07/owl#ObjectProperty>,
                        <http://www.w3.org/2002/07/owl#DatatypeProperty>
                    ))
                }}
            }}
            """
            prop_result = agent.anzo_client.query_journal(prop_count_query)
            prop_table = prop_result.as_table_results().as_list()
            prop_count = int(prop_table[0][0]) if prop_table and prop_table[0] and prop_table[0][0] else 0
        except Exception:
            prop_count = 0
        
        # Extract title from URI
        title = ontology_uri.split('/')[-1] if '/' in ontology_uri else ontology_uri
        if '#' in title:
            title = title.split('#')[0]
        
        ontologies.append({
            "uri": ontology_uri,
            "title": title,
            "class_count": class_count,
            "property_count": prop_count,
            "discovery_method": "AGS Configuration Discovery"
        })
    
    return BaseToolMixin.create_success_response({
        "ontologies": ontologies,
        "total_classes": len(agent.ontology_info.classes),
        "total_properties": len(agent.ontology_info.properties),
        "ontology_count": len(ontologies)
    })