"""
Remove Ontology Property tool for the AGS SPARQL Agent.

This tool handles remove ontology property 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 remove_ontology_property(
    ontology_uri: str,
    property_uri: str,
    explanation: str = None,
    dry_run: bool = False
    ) -> str:
    """Remove a property from an ontology.
    
    This tool removes an OWL property and all its metadata from an ontology.
    
    Args:
        ontology_uri: URI of the ontology to remove the property from (required)
        property_uri: URI of the property to remove (required)
        explanation: Human-readable description of the operation
        dry_run: If true, validate inputs without executing
        
    Returns:
        JSON response with property removal results
    """
    BaseToolMixin.validate_required_param(ontology_uri, "ontology_uri")
    BaseToolMixin.validate_required_param(property_uri, "property_uri")
    BaseToolMixin.validate_uri(ontology_uri, "ontology_uri")
    BaseToolMixin.validate_uri(property_uri, "property_uri")
    
    agent = await get_agent()
    
    # Check if property exists (check for any type of property)
    property_exists_query = f"""SELECT ?type WHERE {{ 
        GRAPH <{ontology_uri}> {{ 
            {{ <{property_uri}> a ?type . FILTER(?type = <http://www.w3.org/2002/07/owl#ObjectProperty>) }}
            UNION
            {{ <{property_uri}> a ?type . FILTER(?type = <http://www.w3.org/2002/07/owl#DatatypeProperty>) }}
            UNION
            {{ <{property_uri}> a ?type . FILTER(?type = <http://www.w3.org/2002/07/owl#AnnotationProperty>) }}
        }} 
    }}"""
    property_exists_result = agent.anzo_client.query_journal(property_exists_query)
    table_results = property_exists_result.as_table_results().as_list()
    property_exists = len(table_results) > 0
    
    if not property_exists:
        return BaseToolMixin.create_success_response({
            "ontology_uri": ontology_uri,
            "property_uri": property_uri,
            "not_found": True,
            "explanation": explanation
        }, f"Property '{property_uri}' does not exist in ontology '{ontology_uri}'")
    
    # Dry run mode
    if dry_run:
        return BaseToolMixin.create_success_response({
            "dry_run": True,
            "ontology_uri": ontology_uri,
            "property_uri": property_uri,
            "explanation": explanation
        }, "Property removal 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'
    
    # Remove the property and all its metadata
    remove_property_sparql = f"""
    PREFIX owl: <http://www.w3.org/2002/07/owl#>
    PREFIX dct: <http://purl.org/dc/terms/>
    
    DELETE {{
        GRAPH <{ontology_uri}> {{
            <{property_uri}> ?p ?o .
            ?s ?p2 <{property_uri}> .
        }}
    }}
    INSERT {{
        GRAPH <{ontology_uri}> {{
            <{ontology_uri}> dct:modified "{current_timestamp}" ;
                            dct:modifier <http://openanzo.org/system/internal/sysadmin> .
        }}
    }}
    WHERE {{
        GRAPH <{ontology_uri}> {{
            {{
                <{property_uri}> ?p ?o .
            }} UNION {{
                ?s ?p2 <{property_uri}> .
            }}
        }}
    }}
    """
    
    # Execute the property removal
    agent.anzo_client.update_journal(remove_property_sparql)
    
    return BaseToolMixin.create_success_response({
        "ontology_uri": ontology_uri,
        "property_uri": property_uri,
        "removed_timestamp": current_timestamp,
        "explanation": explanation
    }, f"Successfully removed property '{property_uri}' from ontology '{ontology_uri}'")