"""
Add Ontology Class tool for the AGS SPARQL Agent.

This tool handles add ontology class 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 add_ontology_class(
    ontology_uri: str,
    class_uri: str,
    class_label: str = None,
    class_description: str = None,
    superclass_uri: str = None,
    explanation: str = None,
    dry_run: bool = False
    ) -> str:
    """Add a new class to an ontology.
    
    This tool adds an OWL class with optional metadata and superclass relationships.
    
    Args:
        ontology_uri: URI of the ontology to add the class to (required)
        class_uri: URI of the new class (required)
        class_label: Human-readable label for the class
        class_description: Description of the class purpose
        superclass_uri: URI of the superclass (optional)
        explanation: Human-readable description of the operation
        dry_run: If true, validate inputs without executing
        
    Returns:
        JSON response with class addition results
    """
    BaseToolMixin.validate_required_param(ontology_uri, "ontology_uri")
    BaseToolMixin.validate_required_param(class_uri, "class_uri")
    BaseToolMixin.validate_uri(ontology_uri, "ontology_uri")
    BaseToolMixin.validate_uri(class_uri, "class_uri")
    
    if superclass_uri:
        BaseToolMixin.validate_uri(superclass_uri, "superclass_uri")
    
    agent = await get_agent()
    
    # Check if ontology exists
    exists_query = f"SELECT ?o WHERE {{ GRAPH <{ontology_uri}> {{ <{ontology_uri}> a ?o }} }}"
    exists_result = agent.anzo_client.query_journal(exists_query)
    table_results = exists_result.as_table_results().as_list()
    ontology_exists = len(table_results) > 0
    
    if not ontology_exists:
        raise ToolError(f"Ontology '{ontology_uri}' not found")
    
    # Check if class already exists
    class_exists_query = f"SELECT ?type WHERE {{ GRAPH <{ontology_uri}> {{ <{class_uri}> a ?type . FILTER(?type = <http://www.w3.org/2002/07/owl#Class>) }} }}"
    class_exists_result = agent.anzo_client.query_journal(class_exists_query)
    table_results = class_exists_result.as_table_results().as_list()
    class_already_exists = len(table_results) > 0
    
    if class_already_exists:
        return BaseToolMixin.create_success_response({
            "ontology_uri": ontology_uri,
            "class_uri": class_uri,
            "already_exists": True,
            "explanation": explanation
        }, f"Class '{class_uri}' already exists in ontology '{ontology_uri}'")
    
    # Dry run mode
    if dry_run:
        return BaseToolMixin.create_success_response({
            "dry_run": True,
            "ontology_uri": ontology_uri,
            "class_uri": class_uri,
            "class_label": class_label,
            "class_description": class_description,
            "superclass_uri": superclass_uri,
            "explanation": explanation
        }, "Class addition validated. Set dry_run=false to execute.")
    
    # Get current timestamp for metadata
    current_timestamp = datetime.now().strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'
    
    # Build the class definition
    class_triples = [f"<{class_uri}> a <http://www.w3.org/2002/07/owl#Class>"]
    
    if class_label:
        class_triples.append(f'<{class_uri}> <http://www.w3.org/2000/01/rdf-schema#label> "{class_label}"')
    
    if class_description:
        class_triples.append(f'<{class_uri}> <http://purl.org/dc/elements/1.1/description> "{class_description}"')
    
    if superclass_uri:
        class_triples.append(f"<{class_uri}> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <{superclass_uri}>")
    
    # Add metadata
    class_triples.extend([
        f'<{class_uri}> <http://purl.org/dc/terms/created> "{current_timestamp}"',
        f'<{class_uri}> <http://purl.org/dc/terms/creator> <http://openanzo.org/system/internal/sysadmin>',
        f'<{ontology_uri}> <http://purl.org/dc/terms/modified> "{current_timestamp}"',
        f'<{ontology_uri}> <http://purl.org/dc/terms/modifier> <http://openanzo.org/system/internal/sysadmin>'
    ])
    
    # Create the INSERT statement
    add_class_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/>
    
    INSERT DATA {{
        GRAPH <{ontology_uri}> {{
            {' . '.join(class_triples)} .
        }}
    }}
    """
    
    # Execute the class addition
    agent.anzo_client.update_journal(add_class_sparql)
    
    return BaseToolMixin.create_success_response({
        "ontology_uri": ontology_uri,
        "class_uri": class_uri,
        "class_label": class_label,
        "class_description": class_description,
        "superclass_uri": superclass_uri,
        "added_timestamp": current_timestamp,
        "explanation": explanation
    }, f"Successfully added class '{class_uri}' to ontology '{ontology_uri}'")