import type { CallToolResult } from "@modelcontextprotocol/server";
import type { ProblemBody } from "@/app/api/v3/lib/response";

type TMcpSuccessPayload = Record<string, unknown> & {
  requestId: string;
};

type TMcpErrorPayload = {
  error: {
    status: number;
    title: string;
    detail: string;
    requestId: string;
    code?: string;
    // ENG-3069: a 409 carries `expectedUpdatedAt`/`currentUpdatedAt` here. Dropping it would leave an
    // agent with a retry it cannot perform — it would have to re-read the whole survey to learn the
    // timestamp the error already knew.
    details?: NonNullable<ProblemBody["details"]>;
    invalid_params?: NonNullable<ProblemBody["invalid_params"]>;
  };
};

function toTextResult(payload: TMcpSuccessPayload | TMcpErrorPayload, isError = false): CallToolResult {
  return {
    ...(isError ? { isError: true } : {}),
    structuredContent: payload,
    content: [
      {
        type: "text",
        text: JSON.stringify(payload),
      },
    ],
  };
}

function isPlainRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}

async function readJsonResponse(response: Response): Promise<Record<string, unknown>> {
  try {
    const body = await response.json();
    return body && typeof body === "object" ? (body as Record<string, unknown>) : {};
  } catch {
    return {};
  }
}

export async function responseToMcpToolResult(
  response: Response,
  fallbackRequestId: string
): Promise<CallToolResult> {
  const body = await readJsonResponse(response);
  const requestId =
    typeof body.requestId === "string"
      ? body.requestId
      : (response.headers.get("X-Request-Id") ?? fallbackRequestId);

  if (response.ok) {
    return toTextResult({
      ...body,
      requestId,
    });
  }

  const problem = body as Partial<ProblemBody>;
  return toTextResult(
    {
      error: {
        status: response.status,
        title: typeof problem.title === "string" ? problem.title : "Error",
        detail: typeof problem.detail === "string" ? problem.detail : response.statusText || "Request failed",
        requestId,
        ...(typeof problem.code === "string" ? { code: problem.code } : {}),
        ...(isPlainRecord(problem.details) ? { details: problem.details } : {}),
        ...(Array.isArray(problem.invalid_params) ? { invalid_params: problem.invalid_params } : {}),
      },
    },
    true
  );
}

/**
 * The answer to a tool call that was denied something because the request's grant doesn't reach it
 * (ADR-0042): one not found, with nothing taken from the operation's own body, so an id outside the grant
 * and an id that doesn't exist read alike and the client can't learn what else exists. The tool guard
 * calls it only for an error answer of a call during which `can()` or a list lookup denied on the grant's
 * reach (`runRecordingMcpReachDenials`); every other answer passes through unchanged.
 */
export const mcpOutsideGrantResult = (requestId: string): CallToolResult =>
  toTextResult(
    {
      error: {
        status: 404,
        title: "Not Found",
        code: "not_found",
        detail: "Not found. It doesn't exist, or the user's grant to this MCP client doesn't reach it.",
        requestId,
      },
    },
    true
  );
