"""
Shared utility functions for the Siemens Graph Studio MCP Server.

This module provides common utilities used across multiple tool modules.
"""

import os
import sys
from typing import Optional


async def get_agent():
    """Get the shared SPARQL agent instance."""
    # Import here to avoid circular imports
    from .. import server
    return await server.get_agent()


def get_graphmart_uri(provided_uri: Optional[str] = None) -> str:
    """Get graphmart URI from parameter or environment."""
    if provided_uri:
        return provided_uri
    
    uri = os.getenv('GRAPHMART_URI')
    if not uri:
        raise ValueError("No graphmart URI provided and GRAPHMART_URI environment variable not set")
    
    return uri


def extract_ontology_from_uri(uri: str) -> str:
    """Extract ontology base URI from a class or property URI."""
    if not uri:
        return None
    
    # Handle different URI patterns
    if '#' in uri:
        # Pattern: https://example.com/ontology#ClassName -> https://example.com/ontology
        return uri.split('#')[0]
    elif '/ontology/' in uri:
        # Pattern: https://example.com/ontology/subdirectory/ClassName -> https://example.com/ontology/subdirectory
        parts = uri.split('/')
        try:
            ont_index = parts.index('ontology')
            # Include everything up to and including the first path segment after 'ontology'
            if ont_index + 2 < len(parts):
                return '/'.join(parts[:ont_index + 2])
            else:
                return '/'.join(parts[:ont_index + 1])
        except ValueError:
            pass
    elif '/ontologies/' in uri:
        # Pattern: https://example.com/ontologies/OntologyName/... -> https://example.com/ontologies/OntologyName
        parts = uri.split('/')
        try:
            onts_index = parts.index('ontologies')
            if onts_index + 2 < len(parts):
                return '/'.join(parts[:onts_index + 2])
            else:
                return '/'.join(parts[:onts_index + 1])
        except ValueError:
            pass
    
    # Fallback: remove last path segment
    if '/' in uri:
        return '/'.join(uri.split('/')[:-1])
    
    return uri


# XSD datatypes for property classification
XSD_DATATYPES = {
    "http://www.w3.org/2001/XMLSchema#string",
    "http://www.w3.org/2001/XMLSchema#integer",
    "http://www.w3.org/2001/XMLSchema#int",
    "http://www.w3.org/2001/XMLSchema#decimal",
    "http://www.w3.org/2001/XMLSchema#float",
    "http://www.w3.org/2001/XMLSchema#double",
    "http://www.w3.org/2001/XMLSchema#date",
    "http://www.w3.org/2001/XMLSchema#boolean",
    "http://www.w3.org/2001/XMLSchema#long",
    "http://www.w3.org/2001/XMLSchema#literal",
}