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

This tool handles delete 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 delete_ontology(
    ontology_uri: str,
    explanation: str = None,
    dry_run: bool = False
    ) -> str:
    """Delete an ontology and all its content.
    
    This tool removes an ontology graph and all its triples from AGS.
    Use with caution as this operation cannot be undone.
    
    Args:
        ontology_uri: URI of the ontology to delete (required)
        explanation: Human-readable description of the operation
        dry_run: If true, validate inputs without executing
        
    Returns:
        JSON response with deletion results
    """
    BaseToolMixin.validate_required_param(ontology_uri, "ontology_uri")
    
    agent = await get_agent()
    
    # Check if ontology exists
    exists_query = f"SELECT ?s WHERE {{ GRAPH <{ontology_uri}> {{ ?s ?p ?o }} }} LIMIT 1"
    
    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")
    
    # Count triples for reporting
    count_query = f"""
    SELECT (COUNT(*) AS ?count) WHERE {{
        GRAPH <{ontology_uri}> {{
            ?s ?p ?o .
        }}
    }}
    """
    
    count_result = agent.anzo_client.query_journal(count_query)
    count_table = count_result.as_table_results().as_list()
    triple_count = 0
    if count_table and len(count_table) > 0 and count_table[0]:
        try:
            triple_count = int(count_table[0][0])
        except (ValueError, TypeError):
            triple_count = 0
    
    # Dry run mode
    if dry_run:
        return BaseToolMixin.create_success_response({
            "dry_run": True,
            "ontology_uri": ontology_uri,
            "triple_count": triple_count,
            "explanation": explanation
        }, f"Ontology deletion validated. Would delete {triple_count} triples. Set dry_run=false to execute.")
    
    # Get graphmart URI for cleanup
    graphmart_uri = get_graphmart_uri()
    
    # Step 1: Remove from ontology registry
    registry_cleanup = f"""
    WITH <http://cambridgesemantics.com/registries/Ontologies>
    DELETE {{
        <http://cambridgesemantics.com/registries/Ontologies>
            <http://openanzo.org/ontologies/2008/07/Anzo#defaultNamedGraph>
            <{ontology_uri}> .
    }}
    WHERE {{
        <http://cambridgesemantics.com/registries/Ontologies>
            <http://openanzo.org/ontologies/2008/07/Anzo#defaultNamedGraph>
            <{ontology_uri}> .
    }}
    """
    
    # Step 2: Remove from graphmart model
    graphmart_cleanup = f"""
    WITH <{graphmart_uri}>
    DELETE {{
        <{graphmart_uri}>
            <http://cambridgesemantics.com/ontologies/Graphmarts#model>
            <{ontology_uri}> .
    }}
    WHERE {{
        <{graphmart_uri}>
            <http://cambridgesemantics.com/ontologies/Graphmarts#model>
            <{ontology_uri}> .
    }}
    """
    
    # Step 3: Remove log file entries
    logfiles_cleanup = f"""
    WITH <http://cambridgesemantics.com/registries/LogFiles>
    DELETE {{
        ?logFile <http://openanzo.org/ontologies/2008/07/System#sourceURI> <{ontology_uri}> .
    }}
    WHERE {{
        ?logFile <http://openanzo.org/ontologies/2008/07/System#sourceURI> <{ontology_uri}> .
    }}
    """
    
    # Step 4: Delete the entire ontology graph
    delete_ontology_sparql = f"""
    DROP GRAPH <{ontology_uri}>
    """
    
    # Execute all cleanup operations
    agent.anzo_client.update_journal(registry_cleanup)
    agent.anzo_client.update_journal(graphmart_cleanup)
    agent.anzo_client.update_journal(logfiles_cleanup)
    agent.anzo_client.update_journal(delete_ontology_sparql)
    
    return BaseToolMixin.create_success_response({
        "ontology_uri": ontology_uri,
        "deleted_triple_count": triple_count,
        "explanation": explanation
    }, f"Successfully deleted ontology '{ontology_uri}' with {triple_count} triples")