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

This tool discovers and profiles all datatype properties (string, int, date, etc.) 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_data_properties(class_uri: str) -> str:
    """Discover datatype properties for a specific class.
    
    This tool discovers and profiles all datatype properties (string, int, date, etc.) 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 datatype 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 datatype properties for the class
    properties = []
    for prop_info in agent.ontology_info.properties.values():
        if class_uri in prop_info.domain_classes:
            is_datatype_property = False
            if prop_info.range_classes:
                for range_uri in prop_info.range_classes:
                    if range_uri in XSD_DATATYPES:
                        is_datatype_property = True
                        break
            else:
                # If no range specified, assume datatype property
                is_datatype_property = True
                
            if is_datatype_property:
                # Infer data type from range
                data_type = "string"  # default
                if prop_info.range_classes:
                    range_uri = prop_info.range_classes[0]
                    if range_uri == "http://www.w3.org/2001/XMLSchema#integer" or range_uri == "http://www.w3.org/2001/XMLSchema#int":
                        data_type = "integer"
                    elif range_uri in ["http://www.w3.org/2001/XMLSchema#decimal", "http://www.w3.org/2001/XMLSchema#float", "http://www.w3.org/2001/XMLSchema#double"]:
                        data_type = "decimal"
                    elif range_uri == "http://www.w3.org/2001/XMLSchema#date":
                        data_type = "date"
                    elif range_uri == "http://www.w3.org/2001/XMLSchema#boolean":
                        data_type = "boolean"
                        
                properties.append({
                    "property_uri": prop_info.uri,
                    "property_name": prop_info.name,
                    "data_type": data_type,
                    "range": prop_info.range_classes[0] if prop_info.range_classes else None,
                    "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,
        "datatype_properties": properties,
        "property_count": len(properties)
    })