"""
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

# Module-level cache for the REST API client
_rest_api_client = None


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_rest_api_client():
    """Get a cached AnzoRestClient instance.

    Uses the same ANZO_SERVER, ANZO_PORT, ANZO_USERNAME, ANZO_PASSWORD
    environment variables as the journal-based agent.

    Returns:
        AnzoRestClient instance configured for the current environment.

    Raises:
        ValueError: If required environment variables are missing.
    """
    global _rest_api_client
    if _rest_api_client is not None:
        return _rest_api_client

    from .rest_api_utils import AnzoRestClient

    hostname = os.getenv("ANZO_SERVER")
    port = os.getenv("ANZO_PORT", "443")
    username = os.getenv("ANZO_USERNAME")
    password = os.getenv("ANZO_PASSWORD")

    if not hostname or not username or not password:
        raise ValueError(
            "REST API client requires ANZO_SERVER, ANZO_USERNAME, and "
            "ANZO_PASSWORD environment variables"
        )

    _rest_api_client = AnzoRestClient(
        hostname=hostname,
        port=int(port),
        username=username,
        password=password,
    )
    return _rest_api_client


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",
}