"""
Class object properties discovery tool for the AGS SPARQL Agent.

This tool discovers and profiles all object properties (relationships to other classes)
that can be used with instances of the specified class, including usage statistics.
"""

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, XSD_DATATYPES


@handle_tool_errors
async def discover_class_object_properties(class_uri: str) -> str:
    """Discover object properties for a specific class.
    
    This tool discovers and profiles all object properties (relationships to other classes)
    that can be used with instances of the specified class, including usage statistics.
    
    Args:
        class_uri: URI of the class to explore
        
    Returns:
        JSON response with object property list and details
    """
    BaseToolMixin.validate_required_param(class_uri, "class_uri")
    BaseToolMixin.validate_uri(class_uri, "class_uri")
    
    agent = await get_agent()
    
    # Use in-memory ontology info
    if not agent.ontology_info:
        raise ToolError("No ontology information loaded")
    
    # Find object properties for the class
    properties = []
    for prop_info in agent.ontology_info.properties.values():
        if class_uri in prop_info.domain_classes:
            is_object_property = False
            if prop_info.range_classes:
                for range_uri in prop_info.range_classes:
                    if range_uri not in XSD_DATATYPES:
                        is_object_property = True
                        break
                        
            # If no range, do not classify as object property
            if is_object_property:
                range_class_names = []
                for range_uri in prop_info.range_classes:
                    range_name = (range_uri.split('#')[-1] if '#' in range_uri else 
                                range_uri.split('/')[-1])
                    range_class_names.append(range_name)
                    
                properties.append({
                    "property_uri": prop_info.uri,
                    "property_name": prop_info.name,
                    "domains": list(prop_info.domain_classes),
                    "ranges": list(prop_info.range_classes),
                    "range_class_names": range_class_names,
                    "usage_frequency": prop_info.usage_frequency,
                    "has_usage": prop_info.has_usage()
                })
    
    # Sort by usage frequency (descending) then by property URI
    properties.sort(key=lambda p: (-p["usage_frequency"] if p["usage_frequency"] else 0, p["property_uri"]))
    
    return BaseToolMixin.create_success_response({
        "class_uri": class_uri,
        "object_properties": properties,
        "property_count": len(properties)
    })