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

This tool discovers and profiles classes that have actual instances in the knowledge graph,
providing usage statistics and discovery information.
"""

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_ontology_classes(ontology_uri: str) -> str:
    """Discover classes with actual data instances in a specific ontology.
    
    This tool discovers and profiles classes that have actual instances in the knowledge graph,
    providing usage statistics and discovery information. Use this to see what classes have data you can query.
    
    Args:
        ontology_uri: URI of the ontology to explore
        
    Returns:
        JSON response with populated class list and instance counts
    """
    BaseToolMixin.validate_required_param(ontology_uri, "ontology_uri")
    BaseToolMixin.validate_uri(ontology_uri, "ontology_uri")
    
    agent = await get_agent()
    
    # Use in-memory ontology info
    if not agent.ontology_info:
        raise ToolError("No ontology information loaded")
    
    # Filter classes by ontology using cached ontology_uri
    matching_classes = []
    for class_info in agent.ontology_info.classes.values():
        # Use the cached ontology_uri to filter classes (much faster than SPARQL queries)
        if hasattr(class_info, 'ontology_uri') and class_info.ontology_uri == ontology_uri:
            matching_classes.append({
                "uri": class_info.uri,
                "name": class_info.name,
                "description": class_info.description,
                "instance_count": class_info.instance_count,
                "has_instances": class_info.has_instances()
            })
    
    # Sort by instance count (descending) then by URI for consistent output
    matching_classes.sort(key=lambda c: (-c["instance_count"] if c["instance_count"] else 0, c["uri"]))
    
    return BaseToolMixin.create_success_response({
        "ontology_uri": ontology_uri,
        "classes": matching_classes,
        "class_count": len(matching_classes)
    })