"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { Wand2 } from "lucide-react";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Alert, AlertTitle } from "../../primitives/alert.js";
import { Button } from "../../primitives/button.js";
import { useAiPendingActionPolling } from "./useAiPendingActionPolling.js";
const AI_CHAT_FIX_REQUEST_EVENT = "om-ai-chat-fix-request";
function dispatchFixRequest(detail) {
  if (typeof window === "undefined") return;
  window.dispatchEvent(new CustomEvent(AI_CHAT_FIX_REQUEST_EVENT, { detail }));
}
function isSuccessStatus(status) {
  return status === "confirmed";
}
function isFailureStatus(status) {
  return status === "failed" || status === "cancelled" || status === "expired";
}
function MutationResultCard(props) {
  const t = useT();
  const pendingActionId = props.pendingActionId ?? "";
  const payload = props.payload ?? {};
  const injected = props.initialAction ?? payload.pendingAction ?? null;
  const { action: polled } = useAiPendingActionPolling({
    pendingActionId,
    endpoint: props.endpoint,
    disabled: !pendingActionId || Boolean(injected)
  });
  const action = injected ?? polled;
  const status = action?.status ?? null;
  const failedRecords = action?.failedRecords ?? null;
  const result = action?.executionResult ?? null;
  if (!action) {
    return null;
  }
  if (isSuccessStatus(status) && failedRecords && failedRecords.length > 0) {
    return /* @__PURE__ */ jsxs(Alert, { variant: "warning", "data-ai-mutation-result": "partial", children: [
      /* @__PURE__ */ jsx(AlertTitle, { children: t(
        "ai_assistant.chat.mutation_cards.result.partialTitle",
        "Action applied with failures"
      ) }),
      /* @__PURE__ */ jsxs("div", { className: "text-sm leading-relaxed", children: [
        /* @__PURE__ */ jsx("p", { children: t(
          "ai_assistant.chat.mutation_cards.result.partialBody",
          "Some records could not be updated."
        ) }),
        /* @__PURE__ */ jsx(
          "ul",
          {
            className: "mt-2 list-disc space-y-1 pl-5 text-xs",
            "data-ai-mutation-failed-records": true,
            children: failedRecords.map((record) => /* @__PURE__ */ jsxs("li", { "data-ai-mutation-failed-record": record.recordId, children: [
              /* @__PURE__ */ jsx("span", { className: "font-mono", children: record.recordId }),
              /* @__PURE__ */ jsx("span", { className: "mx-1 text-muted-foreground", children: "\u2022" }),
              /* @__PURE__ */ jsx("span", { className: "font-mono", children: record.error.code }),
              /* @__PURE__ */ jsx("span", { className: "mx-1 text-muted-foreground", children: "\u2014" }),
              /* @__PURE__ */ jsx("span", { children: record.error.message })
            ] }, record.recordId))
          }
        )
      ] })
    ] });
  }
  if (isSuccessStatus(status)) {
    const recordId = result?.recordId ?? action.targetRecordId ?? null;
    const href = payload.recordHref ?? null;
    return /* @__PURE__ */ jsxs(Alert, { variant: "success", "data-ai-mutation-result": "success", children: [
      /* @__PURE__ */ jsx(AlertTitle, { children: t("ai_assistant.chat.mutation_cards.result.successTitle", "Action applied") }),
      /* @__PURE__ */ jsxs("div", { className: "text-sm leading-relaxed", children: [
        /* @__PURE__ */ jsx("p", { children: t(
          "ai_assistant.chat.mutation_cards.result.successBody",
          "The requested change was saved successfully."
        ) }),
        recordId && href ? /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs", children: /* @__PURE__ */ jsx(
          "a",
          {
            className: "text-primary underline",
            href,
            "data-ai-mutation-result-link": true,
            children: t(
              "ai_assistant.chat.mutation_cards.result.viewRecord",
              "View record"
            )
          }
        ) }) : null
      ] })
    ] });
  }
  if (isFailureStatus(status) || result?.error) {
    const code = result?.error?.code ?? status ?? "failed";
    const message = result?.error?.message ?? t(
      "ai_assistant.chat.mutation_cards.result.failureBody",
      "The mutation could not be applied."
    );
    const errorObj = result?.error;
    const errorDetails = errorObj?.details;
    const errorInput = errorObj?.input;
    const errorName = errorObj?.name;
    const onFixWithAi = () => {
      const promptLines = [
        `The previous call to tool "${action.toolName}" failed.`,
        `Error: ${code} \u2014 ${message}.`
      ];
      if (errorName && errorName !== "Error") {
        promptLines.push(`Error class: ${errorName}.`);
      }
      if (action.targetEntityType || action.targetRecordId) {
        promptLines.push(
          `Target: ${action.targetEntityType ?? "?"}${action.targetRecordId ? " / " + action.targetRecordId : ""}.`
        );
      }
      const issues = errorDetails?.issues ?? [];
      if (Array.isArray(issues) && issues.length > 0) {
        promptLines.push("", "Validation issues:");
        for (const issue of issues) {
          const path = Array.isArray(issue?.path) && issue.path.length > 0 ? issue.path.join(".") : "(root)";
          const msg = issue?.message ?? "(no message)";
          const codeHint = issue?.code ? ` [${issue.code}]` : "";
          const expHint = issue?.expected || issue?.received ? ` (expected ${issue?.expected ?? "?"}, got ${issue?.received ?? "?"})` : "";
          promptLines.push(`- ${path}: ${msg}${codeHint}${expHint}`);
        }
      } else if (errorDetails?.fieldErrors && typeof errorDetails.fieldErrors === "object") {
        const entries = Object.entries(errorDetails.fieldErrors);
        if (entries.length > 0) {
          promptLines.push("", "Field errors:");
          for (const [path, msgs] of entries) {
            const list = Array.isArray(msgs) ? msgs.join("; ") : String(msgs);
            promptLines.push(`- ${path}: ${list}`);
          }
        }
      }
      if (errorInput !== void 0) {
        try {
          const json = JSON.stringify(errorInput, null, 2);
          if (json && json !== "{}" && json.length <= 4e3) {
            promptLines.push("", "Arguments you sent:", "```json", json, "```");
          } else if (json && json.length > 4e3) {
            promptLines.push(
              "",
              "Arguments you sent (truncated):",
              "```json",
              json.slice(0, 4e3) + "\n\u2026 [truncated]",
              "```"
            );
          }
        } catch {
        }
      }
      if (errorDetails?.cause !== void 0) {
        try {
          const causeJson = JSON.stringify(errorDetails.cause, null, 2);
          if (causeJson && causeJson !== "{}" && causeJson.length <= 1500) {
            promptLines.push("", "Underlying cause:", "```json", causeJson, "```");
          }
        } catch {
        }
      }
      if (failedRecords && failedRecords.length > 0) {
        promptLines.push("", "Records that failed:");
        for (const rec of failedRecords) {
          promptLines.push(
            `- ${rec.recordId} \u2192 ${rec.error.code}: ${rec.error.message}`
          );
        }
      }
      promptLines.push(
        "",
        "Diagnose what went wrong using the validation issues / cause / arguments above, correct the arguments, and call the tool again. If the failure indicates missing prerequisites (e.g. a deal needs a linked person/company before commenting), tell me what to fix on the platform side instead of retrying blindly. Do not repeat the exact same arguments \u2014 you must change at least one parameter or stop and explain."
      );
      dispatchFixRequest({
        message: promptLines.join("\n"),
        toolName: action.toolName,
        pendingActionId: action.id
      });
    };
    const visibleIssues = Array.isArray(errorDetails?.issues) ? errorDetails.issues.filter((entry) => entry && (entry.message || entry.path)) : [];
    return /* @__PURE__ */ jsxs(Alert, { variant: "destructive", "data-ai-mutation-result": "failure", children: [
      /* @__PURE__ */ jsx(AlertTitle, { children: t(
        "ai_assistant.chat.mutation_cards.result.failureTitle",
        "Action failed"
      ) }),
      /* @__PURE__ */ jsxs("div", { className: "text-sm leading-relaxed", children: [
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("span", { className: "mr-2 font-mono text-xs", "data-ai-mutation-result-code": true, children: code }),
          /* @__PURE__ */ jsx("span", { children: message })
        ] }),
        visibleIssues.length > 0 ? /* @__PURE__ */ jsx(
          "ul",
          {
            className: "mt-2 list-disc space-y-0.5 pl-5 text-xs",
            "data-ai-mutation-result-issues": true,
            children: visibleIssues.map((issue, index) => {
              const path = Array.isArray(issue?.path) && issue.path.length > 0 ? issue.path.join(".") : null;
              return /* @__PURE__ */ jsxs("li", { children: [
                path ? /* @__PURE__ */ jsx("span", { className: "font-mono", children: path }) : null,
                path && issue?.message ? /* @__PURE__ */ jsx("span", { className: "mx-1", children: "\u2014" }) : null,
                issue?.message ? /* @__PURE__ */ jsx("span", { children: issue.message }) : null
              ] }, index);
            })
          }
        ) : null,
        /* @__PURE__ */ jsx("div", { className: "mt-2 flex items-center gap-2", children: /* @__PURE__ */ jsxs(
          Button,
          {
            type: "button",
            variant: "outline",
            size: "sm",
            onClick: onFixWithAi,
            "data-ai-mutation-result-fix": true,
            children: [
              /* @__PURE__ */ jsx(Wand2, { className: "size-4", "aria-hidden": true }),
              /* @__PURE__ */ jsx("span", { children: t(
                "ai_assistant.chat.mutation_cards.result.fixWithAi",
                "Fix with AI"
              ) })
            ]
          }
        ) })
      ] })
    ] });
  }
  return null;
}
var MutationResultCard_default = MutationResultCard;
export {
  AI_CHAT_FIX_REQUEST_EVENT,
  MutationResultCard,
  MutationResultCard_default as default
};
//# sourceMappingURL=MutationResultCard.js.map
