"""MCP tools for table grouping plugin."""

from __future__ import annotations

import json
from typing import Any, Dict, List, Optional

from .strategy import PrefixGroupingStrategy, list_builtin_strategies


def register_table_grouping_tools(mcp, settings):
    """Register table grouping MCP tools."""

    @mcp.tool()
    def group_tables_by_prefix(
        tables: str,
        erp: str = "enertia",
        custom_prefix_map_json: Optional[str] = None,
    ) -> Dict[str, Any]:
        """Group tables into logical modules using prefix-based strategies.

        tables: Comma-separated table names.
        erp: Built-in ERP prefix map (enertia, sap, oracle_ebs). Ignored if custom_prefix_map_json is set.
        custom_prefix_map_json: Optional JSON dict of prefix->module name.
        """
        table_list = [t.strip() for t in tables.split(",") if t.strip()]
        if not table_list:
            return {"error": "No tables provided"}

        if custom_prefix_map_json:
            prefix_map = json.loads(custom_prefix_map_json)
            strategy = PrefixGroupingStrategy(prefix_map=prefix_map)
        else:
            strategy = PrefixGroupingStrategy.from_builtin(erp)

        groups = strategy.group(table_list)
        return {
            "erp": erp if not custom_prefix_map_json else "custom",
            "total_tables": len(table_list),
            "groups": {k: {"count": len(v), "tables": v} for k, v in groups.items()},
        }

    @mcp.tool()
    def list_grouping_strategies() -> Dict[str, Any]:
        """List available built-in ERP table grouping strategies."""
        strategies = list_builtin_strategies()
        return {"strategies": strategies, "count": len(strategies)}

    return {
        "tools_registered": 2,
        "tools": ["group_tables_by_prefix", "list_grouping_strategies"],
    }
