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

This tool handles register 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 register_ontology(
    ontology_uri: str = None,
    graphmart_uri: str = None,
    explanation: str = None,
    dry_run: bool = False
    ) -> str:
    """Register an ontology with the current graphmart in AGS.
    
    This tool creates graphmart-specific registry relationships. Basic ontology
    discoverability is handled by create_ontology. Use this for graphmart linkage.
    
    Args:
        ontology_uri: URI of the ontology to register (required)
        graphmart_uri: URI of the graphmart (optional, auto-detects)
        explanation: Human-readable description of the operation (required)
        dry_run: If true, validate inputs without executing
        
    Returns:
        JSON response with registration results
    """
    BaseToolMixin.validate_required_param(ontology_uri, "ontology_uri")
    BaseToolMixin.validate_required_param(explanation, "explanation")
    BaseToolMixin.validate_uri(ontology_uri, "ontology_uri")
    
    # Auto-detect graphmart URI if not provided
    graphmart_uri = get_graphmart_uri(graphmart_uri)
    BaseToolMixin.validate_uri(graphmart_uri, "graphmart_uri")
    
    agent = await get_agent()
    
    # Check which specific triples exist
    check_query = f"""
    SELECT ?has_registry_triple ?has_graphmart_triple WHERE {{
        OPTIONAL {{
            GRAPH <http://cambridgesemantics.com/registries/Ontologies> {{
                <http://cambridgesemantics.com/registries/Ontologies> 
                    <http://openanzo.org/ontologies/2008/07/Anzo#defaultNamedGraph>
                    <{ontology_uri}> .
                BIND(true AS ?has_registry_triple)
            }}
        }}
        OPTIONAL {{
            GRAPH <{graphmart_uri}> {{
                <{graphmart_uri}>
                    <http://cambridgesemantics.com/ontologies/Graphmarts#model>
                    <{ontology_uri}> .
                BIND(true AS ?has_graphmart_triple)
            }}
        }}
    }}
    """
    
    try:
        check_result = agent.anzo_client.query_journal(check_query)
        check_table = check_result.as_table_results().as_list()
        if check_table:
            row = check_table[0]
            has_registry_triple = row[0] == "true" if row[0] else False
            has_graphmart_triple = row[1] == "true" if row[1] else False
        else:
            has_registry_triple = False
            has_graphmart_triple = False
    except Exception:
        has_registry_triple = False
        has_graphmart_triple = False
    
    already_registered = has_registry_triple and has_graphmart_triple
    
    # Dry run mode
    if dry_run:
        registration_parts = []
        
        if not has_registry_triple:
            registration_parts.append("registry_triple")
        if not has_graphmart_triple:
            registration_parts.append("graphmart_triple")
        
        return BaseToolMixin.create_success_response({
            "dry_run": True,
            "ontology_uri": ontology_uri,
            "graphmart_uri": graphmart_uri,
            "already_registered": already_registered,
            "has_registry_triple": has_registry_triple,
            "has_graphmart_triple": has_graphmart_triple,
            "triples_to_add": registration_parts,
            "explanation": explanation
        }, f"Registration validated. Will add {len(registration_parts)} missing triples.")
    
    # Skip if already registered
    if already_registered:
        return BaseToolMixin.create_success_response({
            "ontology_uri": ontology_uri,
            "graphmart_uri": graphmart_uri,
            "already_registered": True,
            "explanation": explanation
        }, "Ontology is already fully registered - no changes made")
    
    # Execute registration for missing triples
    start_time = datetime.now()
    registration_parts = []
    
    if not has_registry_triple:
        registration_parts.append(f"""    GRAPH <http://cambridgesemantics.com/registries/Ontologies> {{
    <http://cambridgesemantics.com/registries/Ontologies>
        <http://openanzo.org/ontologies/2008/07/Anzo#defaultNamedGraph>
        <{ontology_uri}> .
    }}""")
    
    if not has_graphmart_triple:
        registration_parts.append(f"""    GRAPH <{graphmart_uri}> {{
    <{graphmart_uri}>
        <http://cambridgesemantics.com/ontologies/Graphmarts#model>
        <{ontology_uri}> .
    }}""")
    
    if registration_parts:
        registration_sparql = "INSERT DATA {\n" + "\n    \n".join(registration_parts) + "\n}"
        agent.anzo_client.update_journal(registration_sparql)
    
    execution_time = (datetime.now() - start_time).total_seconds()
    
    return BaseToolMixin.create_success_response({
        "ontology_uri": ontology_uri,
        "graphmart_uri": graphmart_uri,
        "triples_added": len(registration_parts),
        "execution_time_seconds": execution_time,
        "explanation": explanation
    }, f"Successfully added {len(registration_parts)} missing registration triples")