"""Execution-lookup MCP tools.

Thin wrappers over ``services.execution``: each tool validates params with
Pydantic, delegates to the service layer, and returns a structured dict. The
server pipeline (server.py) handles serialization + response budgeting; these
tools never raise into the MCP layer except ``A360AuthError`` (which the
pipeline lets propagate per the auth contract).

Per the coding rules: tool description <=120 chars, param description <=80
chars, a ``Field(description=...)`` on every parameter.
"""

from __future__ import annotations

from pydantic import BaseModel, Field

from ..auth.auth_manager import AuthManager
from ..services import execution as execution_service
from ..utils.config import ServerConfig
from ..utils.registry import register_tool


# --------------------------------------------------------------------------- #
# get_execution
# --------------------------------------------------------------------------- #
class GetExecutionParams(BaseModel):
    execution_id: str = Field(description="Execution id (NOT deploymentId) from /v3/activity.")


@register_tool(
    "get_execution",
    params=GetExecutionParams,
    description="Fetch one execution's status, message and error detail.",
)
def get_execution(
    config: ServerConfig, auth_manager: AuthManager, params: GetExecutionParams
) -> dict:
    raw = execution_service.fetch_execution(auth_manager, params.execution_id)
    summary = execution_service.parse_execution(raw)
    return {
        "id": summary.id,
        "status": summary.status,
        "message": summary.message,
        "file_id": summary.file_id,
        "deployment_id": summary.deployment_id,
        "bot_name": summary.bot_name,
        "started_on": summary.started_on,
        "completed_on": summary.completed_on,
        "is_failure": execution_service.is_failure_status(summary.status),
        "error": summary.error,
    }


# --------------------------------------------------------------------------- #
# list_executions
# --------------------------------------------------------------------------- #
class ListExecutionsParams(BaseModel):
    deployment_id: str | None = Field(
        default=None, description="Filter by deploymentId ([UNVERIFIED] filterable)."
    )
    status: str | None = Field(default=None, description="Filter by status enum, e.g. RUN_FAILED.")
    limit: int = Field(default=50, ge=1, le=500, description="Max executions to return (capped).")


@register_tool(
    "list_executions",
    params=ListExecutionsParams,
    description="Search execution history via POST /v3/activity/list.",
)
def list_executions(
    config: ServerConfig, auth_manager: AuthManager, params: ListExecutionsParams
) -> dict:
    rows = execution_service.find_executions(
        auth_manager,
        deployment_id=params.deployment_id,
        status=params.status,
        max_items=params.limit,
    )
    return {
        "count": len(rows),
        "executions": rows,
    }
