"""
Create Ontology tool for the AGS SPARQL Agent.

This tool handles create ontology operations.
"""

import os
import sys
from datetime import datetime

# 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, get_graphmart_uri


async def create_ontology(
    ontology_uri: str,
    ontology_label: str = None,
    base_namespace: str = None,
    description: str = None,
    explanation: str = None,
    dry_run: bool = False
    ) -> str:
    """Create a new ontology with basic metadata.
    
    This tool creates a new ontology with standard OWL metadata including
    labels, descriptions, and namespace declarations.
    
    Args:
        ontology_uri: URI of the ontology to create (required)
        ontology_label: Human-readable label for the ontology
        base_namespace: Base namespace URI (defaults to ontology_uri)
        description: Description of the ontology's purpose
        explanation: Human-readable description of the operation
        dry_run: If true, validate inputs without executing
        
    Returns:
        JSON response with ontology creation results
    """
    BaseToolMixin.validate_required_param(ontology_uri, "ontology_uri")
    
    # Default values
    if not ontology_label:
        # Extract label from URI (last part after # or /)
        ontology_label = ontology_uri.split('#')[-1].split('/')[-1]
    
    if not base_namespace:
        base_namespace = ontology_uri if ontology_uri.endswith('#') or ontology_uri.endswith('/') else f"{ontology_uri}#"
    
    if not description:
        description = f"Ontology for {ontology_label}"
    
    # Dry run mode
    if dry_run:
        return BaseToolMixin.create_success_response({
            "dry_run": True,
            "ontology_uri": ontology_uri,
            "ontology_label": ontology_label,
            "base_namespace": base_namespace,
            "description": description,
            "explanation": explanation
        }, "Ontology creation validated. Set dry_run=false to execute.")
    
    agent = await get_agent()
    
    # Get current timestamp for metadata
    current_timestamp = datetime.now().strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'
    
    # Create basic ontology with OWL metadata and registry entry
    create_ontology_sparql = f"""
    PREFIX owl: <http://www.w3.org/2002/07/owl#>
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    PREFIX dc: <http://purl.org/dc/elements/1.1/>
    PREFIX dct: <http://purl.org/dc/terms/>
    PREFIX vann: <http://purl.org/vocab/vann/>
    PREFIX anzo: <http://openanzo.org/ontologies/2008/07/Anzo#>
    
    INSERT DATA {{
        GRAPH <{ontology_uri}> {{
            <{ontology_uri}> a owl:Ontology ;
                            rdfs:label "{ontology_label}" ;
                            dc:description "{description}" ;
                            vann:preferredNamespaceUri "{base_namespace}" ;
                            dct:created "{current_timestamp}" ;
                            dct:creator <http://openanzo.org/system/internal/sysadmin> ;
                            dct:modified "{current_timestamp}" ;
                            dct:modifier <http://openanzo.org/system/internal/sysadmin> .
        }}
        GRAPH <http://cambridgesemantics.com/registries/Ontologies> {{
            <http://cambridgesemantics.com/registries/Ontologies>
                anzo:defaultNamedGraph <{ontology_uri}> .
        }}
    }}
    """
    
    # Execute the ontology creation
    agent.anzo_client.update_journal(create_ontology_sparql)
    
    return BaseToolMixin.create_success_response({
        "ontology_uri": ontology_uri,
        "ontology_label": ontology_label,
        "base_namespace": base_namespace,
        "description": description,
        "created_timestamp": current_timestamp,
        "discoverable": True,
        "explanation": explanation
    }, f"Successfully created and registered ontology '{ontology_label}' at {ontology_uri} - now discoverable in AGS")