"""
Read-only MCP tools for Dynamics 365 / Dataverse.
"""

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 dynamics_doctor(profile: str | None = None) -> Dict[str, Any]:
    diagnostics = dynamics_dataverse_mcp.dataverse_proxy_diagnostics()
    resolved_profile = dynamics_dataverse_mcp.resolve_mcp_profile(profile)
    credentials_ok = True
    credential_error = None
    try:
        dynamics_dataverse_mcp.load_dataverse_credentials(profile=resolved_profile)
    except Exception as exc:
        credentials_ok = False
        credential_error = str(exc)
        if diagnostics["status"] == "ok":
            diagnostics["status"] = "warn"
    diagnostics["credentials"] = {
        "profile": resolved_profile,
        "configured": credentials_ok,
        "error": credential_error,
    }
    return diagnostics


def dynamics_list_tables(
    profile: str | None = None,
    top: int = 200,
    include_managed: bool = True,
) -> Dict[str, Any]:
    client = dynamics_dataverse_mcp.create_dataverse_client(profile=profile)
    return client.list_tables(top=top, include_managed=include_managed)


def dynamics_describe_table(
    table: str,
    profile: str | None = None,
    include_attributes: bool = True,
    attribute_top: int = 500,
) -> Dict[str, Any]:
    client = dynamics_dataverse_mcp.create_dataverse_client(profile=profile)
    return client.describe_table(
        table,
        include_attributes=include_attributes,
        attribute_top=attribute_top,
    )


def dynamics_read_query(
    table: str,
    profile: str | None = None,
    select: List[str] | None = None,
    filter_expr: str | None = None,
    orderby: str | None = None,
    top: int = 100,
    count: bool = False,
) -> Dict[str, Any]:
    client = dynamics_dataverse_mcp.create_dataverse_client(profile=profile)
    return client.read_query(
        table=table,
        select=select,
        filter_expr=filter_expr,
        orderby=orderby,
        top=top,
        count=count,
    )


def get_tools() -> List[ToolTuple]:
    return [
        ("dynamics.doctor", dynamics_doctor, "Check Dataverse MCP runtime prerequisites and credential setup."),
        ("dynamics.list_tables", dynamics_list_tables, "List Dataverse tables (EntityDefinitions)."),
        ("dynamics.describe_table", dynamics_describe_table, "Describe Dataverse table metadata and attributes."),
        ("dynamics.read_query", dynamics_read_query, "Read Dataverse rows from a table using OData query options."),
    ]
