"""MCP Tools for Hierarchy Builder.

Provides 7 unified MCP tools:
- hierarchy_manage: 11 actions (project + node CRUD)
- hierarchy_mapping: 8 actions (source mappings + formulas)
- hierarchy_io: 12 actions (import/export/scripts)
- hierarchy_property: 12 actions (property management)
- hierarchy_backend: 16 actions (NestJS backend sync)
- hierarchy_graph: 5 actions (graph bridge + RAG)
- hierarchy_config: hierarchy-first app config governance + Snowflake sync

AUTO-SYNC FEATURE:
When enabled (default), all write operations (create, update, delete)
automatically sync to the NestJS backend. This ensures the MCP server
and Web UI always reflect the same data without manual sync calls.
"""
import logging
import threading
from typing import Optional, Dict, Any, List

from .unified import (
    dispatch_hierarchy_manage,
    dispatch_hierarchy_mapping,
    dispatch_hierarchy_io,
    dispatch_hierarchy_property,
    dispatch_hierarchy_backend,
    dispatch_hierarchy_graph,
    register_unified_hierarchy_tools,
    _ensure_service,
    _ensure_graph_bridge,
    _ensure_sync_service,
    _ensure_auto_sync,
    _try_init_graph_bridge_stores,
)

# Configure logging
logger = logging.getLogger("hierarchy_mcp_tools")


def register_hierarchy_tools(mcp, data_dir: str = "data"):
    """Register all hierarchy MCP tools with the server."""

    # =====================================================================
    # Register the 6 unified tools first; returns service instance
    # =====================================================================
    service = register_unified_hierarchy_tools(mcp, data_dir)

    # =====================================================================
    # Bootstrap: graph bridge initialization (background thread)
    # =====================================================================
    graph_bridge = _ensure_graph_bridge(data_dir)
    sync_service = _ensure_sync_service()
    auto_sync_manager = _ensure_auto_sync()

    # Register bridge callback with AutoSyncManager
    if auto_sync_manager and graph_bridge:
        auto_sync_manager.add_callback(graph_bridge.on_hierarchy_change)

    # Bootstrap: index existing hierarchies in background on startup
    def _bootstrap_index():
        _try_init_graph_bridge_stores()
        bridge = _ensure_graph_bridge(data_dir)
        if not bridge or not bridge._vector_store:
            return
        try:
            svc = _ensure_service(data_dir)
            for proj in svc.list_projects():
                bridge.reindex_project(proj.get("id", ""))
            logger.info("Hierarchy-Graph Bridge: bootstrap indexing complete")
        except Exception as e:
            logger.debug(f"Bootstrap indexing skipped: {e}")

    bootstrap_thread = threading.Thread(target=_bootstrap_index, daemon=True)
    bootstrap_thread.start()

    logger.info("Registered 7 Hierarchy MCP tools (7 unified)")
    return service  # Return service for potential direct use
