"""
Analyze/plan MCP tools for Dynamics 365 / Dataverse mutations.
"""

from __future__ import annotations

from typing import Any, Callable, Dict, List, Tuple

from g_gremlin import dynamics_dataverse_mcp

ToolTuple = Tuple[str, Callable[..., Dict[str, Any]], str]


def _plan(operation: str, payload: Dict[str, Any]) -> Dict[str, Any]:
    plan = dynamics_dataverse_mcp.build_plan(operation=operation, payload=payload)
    return {
        "plan": plan,
        "plan_hash": plan["plan_hash"],
        "operation": operation,
    }


def dynamics_create_record_plan(table: str, record: Dict[str, Any]) -> Dict[str, Any]:
    payload = {"table": table, "record": record}
    return _plan("create_record", payload)


def dynamics_update_record_plan(table: str, record_id: str, fields: Dict[str, Any]) -> Dict[str, Any]:
    payload = {"table": table, "record_id": record_id, "fields": fields}
    return _plan("update_record", payload)


def dynamics_delete_record_plan(table: str, record_id: str) -> Dict[str, Any]:
    payload = {"table": table, "record_id": record_id}
    return _plan("delete_record", payload)


def dynamics_create_table_plan(definition: Dict[str, Any]) -> Dict[str, Any]:
    payload = {"definition": definition}
    return _plan("create_table", payload)


def dynamics_update_table_plan(table: str, definition: Dict[str, Any]) -> Dict[str, Any]:
    payload = {"table": table, "definition": definition}
    return _plan("update_table", payload)


def dynamics_delete_table_plan(table: str) -> Dict[str, Any]:
    payload = {"table": table}
    return _plan("delete_table", payload)


def get_tools() -> List[ToolTuple]:
    return [
        ("dynamics.create_record.plan", dynamics_create_record_plan, "Create plan_hash for a Dataverse create_record."),
        ("dynamics.update_record.plan", dynamics_update_record_plan, "Create plan_hash for a Dataverse update_record."),
        ("dynamics.delete_record.plan", dynamics_delete_record_plan, "Create plan_hash for a Dataverse delete_record."),
        ("dynamics.create_table.plan", dynamics_create_table_plan, "Create plan_hash for a Dataverse create_table."),
        ("dynamics.update_table.plan", dynamics_update_table_plan, "Create plan_hash for a Dataverse update_table."),
        ("dynamics.delete_table.plan", dynamics_delete_table_plan, "Create plan_hash for a Dataverse delete_table."),
    ]
