"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { useQuery } from "@tanstack/react-query";
import { Bot, BookOpen, Loader2, Play, RefreshCcw } from "lucide-react";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Alert, AlertDescription, AlertTitle } from "@open-mercato/ui/primitives/alert";
import { Button } from "@open-mercato/ui/primitives/button";
import { IconButton } from "@open-mercato/ui/primitives/icon-button";
import { Label } from "@open-mercato/ui/primitives/label";
import { Switch } from "@open-mercato/ui/primitives/switch";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@open-mercato/ui/primitives/tabs";
import { Textarea } from "@open-mercato/ui/primitives/textarea";
import { EmptyState } from "@open-mercato/ui/backend/EmptyState";
import { apiCall, apiCallOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { AiChat, createAiUiPartRegistry, LoopDisabledBanner, useAiShortcuts } from "@open-mercato/ui/ai";
import { ConversationShareButton } from "../../../../components/ConversationShareButton.js";
async function fetchAgents() {
  const { result, status } = await apiCallOrThrow(
    "/api/ai_assistant/ai/agents",
    { method: "GET", credentials: "include" },
    { errorMessage: "Failed to load agents" }
  );
  if (!result) throw new Error(`Failed to load agents (${status})`);
  return result;
}
function PlaygroundLoading({ message }) {
  return /* @__PURE__ */ jsxs(
    "div",
    {
      className: "flex items-center gap-2 rounded-lg border border-border bg-background p-4 text-sm text-muted-foreground",
      role: "status",
      children: [
        /* @__PURE__ */ jsx(Loader2, { className: "size-4 animate-spin", "aria-hidden": true }),
        /* @__PURE__ */ jsx("span", { children: message })
      ]
    }
  );
}
function PlaygroundNoAgents() {
  const t = useT();
  return /* @__PURE__ */ jsx(
    EmptyState,
    {
      icon: /* @__PURE__ */ jsx(Bot, { className: "size-6", "aria-hidden": true }),
      title: t(
        "ai_assistant.playground.empty.title",
        "No AI agents are registered for your role yet."
      ),
      description: t(
        "ai_assistant.playground.empty.description",
        "Declare agents inside `packages/<module>/src/modules/<module>/ai-agents.ts`, run `yarn generate`, and ensure the caller holds the agent's required features."
      ),
      children: /* @__PURE__ */ jsxs("div", { className: "mt-2 inline-flex items-center gap-2 text-xs text-muted-foreground", children: [
        /* @__PURE__ */ jsx(BookOpen, { className: "size-3", "aria-hidden": true }),
        /* @__PURE__ */ jsx("span", { children: t(
          "ai_assistant.playground.empty.docLabel",
          "See packages/ai-assistant/AGENTS.md for the agent definition reference."
        ) })
      ] })
    }
  );
}
function AgentDetails({ agent }) {
  const t = useT();
  return /* @__PURE__ */ jsxs("div", { className: "rounded-md border border-border bg-muted/30 p-3 text-sm", children: [
    /* @__PURE__ */ jsx("div", { className: "font-semibold", children: agent.label }),
    /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs text-muted-foreground", children: agent.description }),
    /* @__PURE__ */ jsxs("dl", { className: "mt-3 grid grid-cols-2 gap-2 text-xs", children: [
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx("dt", { className: "font-medium text-muted-foreground", children: t("ai_assistant.playground.meta.module", "Module") }),
        /* @__PURE__ */ jsx("dd", { className: "font-mono", children: agent.moduleId })
      ] }),
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx("dt", { className: "font-medium text-muted-foreground", children: t("ai_assistant.playground.meta.executionMode", "Execution mode") }),
        /* @__PURE__ */ jsx("dd", { className: "font-mono", children: agent.executionMode })
      ] }),
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx("dt", { className: "font-medium text-muted-foreground", children: t("ai_assistant.playground.meta.mutationPolicy", "Mutation policy") }),
        /* @__PURE__ */ jsx("dd", { className: "font-mono", children: agent.mutationPolicy })
      ] }),
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx("dt", { className: "font-medium text-muted-foreground", children: t("ai_assistant.playground.meta.tools", "Allowed tools") }),
        /* @__PURE__ */ jsx("dd", { className: "font-mono", children: agent.allowedTools.length })
      ] })
    ] })
  ] });
}
function buildDebugTools(agent) {
  if (agent.tools && agent.tools.length > 0) {
    return agent.tools.map((tool) => ({
      name: tool.name,
      displayName: tool.displayName ?? tool.name,
      isMutation: Boolean(tool.isMutation),
      requiredFeatures: tool.requiredFeatures ?? []
    }));
  }
  return agent.allowedTools.map((toolName) => ({ name: toolName }));
}
function buildDebugPromptSections(agent) {
  const sections = [];
  if (agent.systemPrompt) {
    sections.push({ id: "role", source: "default", text: agent.systemPrompt });
  }
  const placeholderIds = [
    "scope",
    "data",
    "tools",
    "attachments",
    "mutationPolicy",
    "responseStyle",
    "overrides"
  ];
  for (const id of placeholderIds) {
    sections.push({ id, source: "placeholder" });
  }
  return sections;
}
async function fetchAgentResolutions() {
  const result = await apiCall("/api/ai_assistant/settings");
  if (!result.ok || !result.result) return { agents: [] };
  return { agents: result.result.agents ?? [] };
}
async function fetchLoopOverrideForAgent(agentId) {
  const result = await apiCall(
    `/api/ai_assistant/ai/agents/${encodeURIComponent(agentId)}/loop-override`,
    { method: "GET", credentials: "include" }
  );
  if (!result.ok || !result.result) return { agentId, override: null };
  return result.result;
}
function LoopDisabledPlaygroundBanner({ agentId }) {
  const { data } = useQuery({
    queryKey: ["ai_assistant", "loop_override", agentId],
    queryFn: () => fetchLoopOverrideForAgent(agentId),
    staleTime: 3e4
  });
  if (!data?.override?.loopDisabled) return null;
  return /* @__PURE__ */ jsx(LoopDisabledBanner, { agentId });
}
function ModelResolutionPanel({ agentId }) {
  const t = useT();
  const { data } = useQuery({
    queryKey: ["ai_assistant", "settings", "agents"],
    queryFn: fetchAgentResolutions,
    staleTime: 3e4
  });
  const resolution = data?.agents.find((agent) => agent.agentId === agentId);
  if (!resolution) return null;
  return /* @__PURE__ */ jsxs(
    "dl",
    {
      className: "grid grid-cols-2 gap-x-4 gap-y-1 rounded-md border border-border bg-muted/30 p-3 text-xs sm:grid-cols-4",
      "data-ai-playground-model-resolution": agentId,
      children: [
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("dt", { className: "font-medium text-muted-foreground", children: t("ai_assistant.playground.resolution.provider", "Provider") }),
          /* @__PURE__ */ jsx("dd", { className: "font-mono", "data-ai-playground-resolution-provider": true, children: resolution.providerId })
        ] }),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("dt", { className: "font-medium text-muted-foreground", children: t("ai_assistant.playground.resolution.model", "Model") }),
          /* @__PURE__ */ jsx("dd", { className: "font-mono", "data-ai-playground-resolution-model": true, children: resolution.modelId })
        ] }),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("dt", { className: "font-medium text-muted-foreground", children: t("ai_assistant.playground.resolution.baseUrl", "Base URL") }),
          /* @__PURE__ */ jsx("dd", { className: "font-mono", "data-ai-playground-resolution-base-url": true, children: resolution.baseURL ?? t("ai_assistant.playground.resolution.none", "\u2014") })
        ] }),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("dt", { className: "font-medium text-muted-foreground", children: t("ai_assistant.playground.resolution.source", "Source") }),
          /* @__PURE__ */ jsx("dd", { className: "font-mono", "data-ai-playground-resolution-source": true, children: resolution.source })
        ] })
      ]
    }
  );
}
function readPlaygroundUiPartSeeds() {
  if (typeof window === "undefined") return [];
  try {
    const params = new URLSearchParams(window.location.search);
    const componentId = params.get("uiPart");
    if (!componentId) return [];
    const pendingActionId = params.get("pendingActionId") ?? void 0;
    return [{ componentId, pendingActionId }];
  } catch {
    return [];
  }
}
function ChatLane({ agent, debug }) {
  const t = useT();
  const registry = React.useMemo(
    () => createAiUiPartRegistry({ seedLiveApprovalCards: true }),
    []
  );
  const debugTools = React.useMemo(() => buildDebugTools(agent), [agent]);
  const debugPromptSections = React.useMemo(
    () => buildDebugPromptSections(agent),
    [agent]
  );
  const [uiParts, setUiParts] = React.useState([]);
  const [conversationId, setConversationId] = React.useState(null);
  React.useEffect(() => {
    const seeds = readPlaygroundUiPartSeeds();
    if (seeds.length > 0) setUiParts(seeds);
  }, []);
  if (agent.executionMode !== "chat") {
    return /* @__PURE__ */ jsxs(Alert, { variant: "info", "data-ai-playground-unsupported": "chat", children: [
      /* @__PURE__ */ jsx(AlertTitle, { children: t(
        "ai_assistant.playground.chat.notSupportedTitle",
        "Chat mode is not available for this agent."
      ) }),
      /* @__PURE__ */ jsx(AlertDescription, { children: t(
        "ai_assistant.playground.chat.notSupportedBody",
        'Pick an agent whose execution mode is "chat", or switch to the object-mode tab.'
      ) })
    ] });
  }
  return /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-2", "data-ai-playground-chat": agent.id, children: /* @__PURE__ */ jsx(
    AiChat,
    {
      agent: agent.id,
      pageContext: { source: "playground", pageId: "ai_assistant.playground" },
      debug,
      registry,
      className: "min-h-96",
      debugTools,
      debugPromptSections,
      uiParts,
      onConversationIdChange: setConversationId,
      headerActions: conversationId ? /* @__PURE__ */ jsx(ConversationShareButton, { conversationId }) : null
    },
    agent.id
  ) });
}
function ObjectLane({ agent }) {
  const t = useT();
  const [prompt, setPrompt] = React.useState("");
  const [isRunning, setIsRunning] = React.useState(false);
  const [result, setResult] = React.useState(null);
  const [error, setError] = React.useState(null);
  const [lastRequest, setLastRequest] = React.useState(null);
  const isSupported = agent.executionMode === "object";
  const canRun = isSupported && prompt.trim().length > 0 && !isRunning;
  const runObject = React.useCallback(async () => {
    if (!canRun) return;
    const body = {
      agent: agent.id,
      messages: [{ role: "user", content: prompt }],
      pageContext: { source: "playground", pageId: "ai_assistant.playground" }
    };
    setLastRequest(body);
    setIsRunning(true);
    setResult(null);
    setError(null);
    try {
      const { ok, status, result: result2 } = await apiCall(
        "/api/ai_assistant/ai/run-object",
        {
          method: "POST",
          headers: { "content-type": "application/json" },
          credentials: "include",
          body: JSON.stringify(body)
        }
      );
      if (!ok) {
        const payload = result2 ?? { error: `HTTP ${status}` };
        setError(payload);
        return;
      }
      setResult(result2 ?? { object: null });
    } catch (err) {
      setError({
        error: err instanceof Error ? err.message : String(err),
        code: "network_error"
      });
    } finally {
      setIsRunning(false);
    }
  }, [agent.id, canRun, prompt]);
  const { handleKeyDown } = useAiShortcuts({
    onSubmit: () => {
      void runObject();
    },
    onCancel: () => {
      setError(null);
    }
  });
  if (!isSupported) {
    return /* @__PURE__ */ jsxs(Alert, { variant: "info", "data-ai-playground-unsupported": "object", children: [
      /* @__PURE__ */ jsx(AlertTitle, { children: t(
        "ai_assistant.playground.object.notSupportedTitle",
        "Object mode is not available for this agent."
      ) }),
      /* @__PURE__ */ jsx(AlertDescription, { children: t(
        "ai_assistant.playground.object.notSupportedBody",
        'This agent declares executionMode = "chat". Pick an object-mode agent to preview structured output, or switch to the chat tab.'
      ) })
    ] });
  }
  return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-3", "data-ai-playground-object": true, children: [
    /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2", children: [
      /* @__PURE__ */ jsx(Label, { htmlFor: "ai-playground-object-input", children: t("ai_assistant.playground.object.inputLabel", "Prompt") }),
      /* @__PURE__ */ jsx(
        Textarea,
        {
          id: "ai-playground-object-input",
          rows: 4,
          value: prompt,
          placeholder: t(
            "ai_assistant.playground.object.inputPlaceholder",
            "Describe what the agent should produce..."
          ),
          onChange: (event) => setPrompt(event.target.value),
          onKeyDown: handleKeyDown,
          className: "resize-none",
          "aria-label": t("ai_assistant.playground.object.inputLabel", "Prompt")
        }
      ),
      /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
        /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t(
          "ai_assistant.playground.object.shortcutHint",
          "Press Cmd/Ctrl+Enter to run."
        ) }),
        /* @__PURE__ */ jsxs(
          Button,
          {
            type: "button",
            size: "sm",
            onClick: () => void runObject(),
            disabled: !canRun,
            "data-ai-playground-object-run": true,
            children: [
              isRunning ? /* @__PURE__ */ jsx(Loader2, { className: "size-4 animate-spin", "aria-hidden": true }) : /* @__PURE__ */ jsx(Play, { className: "size-4", "aria-hidden": true }),
              /* @__PURE__ */ jsx("span", { children: t("ai_assistant.playground.object.run", "Run object") })
            ]
          }
        )
      ] })
    ] }),
    error ? /* @__PURE__ */ jsxs(Alert, { variant: "destructive", "data-ai-playground-object-error": error.code ?? "unknown", children: [
      /* @__PURE__ */ jsx(AlertTitle, { children: t("ai_assistant.playground.object.errorTitle", "Object run failed") }),
      /* @__PURE__ */ jsxs(AlertDescription, { children: [
        error.code ? /* @__PURE__ */ jsx("span", { className: "mr-2 font-mono text-xs", children: error.code }) : null,
        error.error
      ] })
    ] }) : null,
    result ? /* @__PURE__ */ jsxs(
      "section",
      {
        className: "rounded-md border border-border bg-muted/30 p-3",
        "data-ai-playground-object-result": true,
        children: [
          /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold", children: t("ai_assistant.playground.object.resultTitle", "Generated object") }),
          /* @__PURE__ */ jsx("pre", { className: "mt-2 max-h-96 overflow-auto rounded bg-background p-2 text-xs font-mono", children: JSON.stringify(result.object, null, 2) }),
          result.usage || result.finishReason ? /* @__PURE__ */ jsxs("dl", { className: "mt-3 grid grid-cols-3 gap-2 text-xs", children: [
            result.finishReason ? /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsx("dt", { className: "text-muted-foreground", children: t("ai_assistant.playground.object.finishReason", "Finish reason") }),
              /* @__PURE__ */ jsx("dd", { className: "font-mono", children: result.finishReason })
            ] }) : null,
            result.usage?.inputTokens !== void 0 ? /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsx("dt", { className: "text-muted-foreground", children: t("ai_assistant.playground.object.inputTokens", "Input tokens") }),
              /* @__PURE__ */ jsx("dd", { className: "font-mono", children: result.usage.inputTokens })
            ] }) : null,
            result.usage?.outputTokens !== void 0 ? /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsx("dt", { className: "text-muted-foreground", children: t("ai_assistant.playground.object.outputTokens", "Output tokens") }),
              /* @__PURE__ */ jsx("dd", { className: "font-mono", children: result.usage.outputTokens })
            ] }) : null
          ] }) : null
        ]
      }
    ) : null,
    lastRequest && (error || result) ? /* @__PURE__ */ jsxs(
      "details",
      {
        className: "rounded-md border border-border bg-muted/20 p-2 text-xs",
        "data-ai-playground-object-debug": true,
        children: [
          /* @__PURE__ */ jsx("summary", { className: "cursor-pointer font-semibold", children: t("ai_assistant.playground.object.debugTitle", "Last request payload") }),
          /* @__PURE__ */ jsx("pre", { className: "mt-2 max-h-64 overflow-auto whitespace-pre-wrap font-mono", children: JSON.stringify(lastRequest, null, 2) })
        ]
      }
    ) : null
  ] });
}
function AiPlaygroundPageClient() {
  const t = useT();
  const [selectedAgentId, setSelectedAgentId] = React.useState(null);
  const [debugEnabled, setDebugEnabled] = React.useState(false);
  const [tab, setTab] = React.useState("chat");
  const { data, isLoading, isError, error, refetch, isFetching } = useQuery({
    queryKey: ["ai_assistant", "playground", "agents"],
    queryFn: fetchAgents
  });
  const agents = React.useMemo(() => data?.agents ?? [], [data]);
  React.useEffect(() => {
    if (!agents.length) {
      if (selectedAgentId !== null) setSelectedAgentId(null);
      return;
    }
    if (!selectedAgentId || !agents.some((agent) => agent.id === selectedAgentId)) {
      setSelectedAgentId(agents[0].id);
    }
  }, [agents, selectedAgentId]);
  const selectedAgent = React.useMemo(() => {
    if (!selectedAgentId) return null;
    return agents.find((agent) => agent.id === selectedAgentId) ?? null;
  }, [agents, selectedAgentId]);
  if (isLoading) {
    return /* @__PURE__ */ jsx(
      PlaygroundLoading,
      {
        message: t("ai_assistant.playground.loadingAgents", "Loading AI agents...")
      }
    );
  }
  if (isError) {
    return /* @__PURE__ */ jsxs(Alert, { variant: "destructive", "data-ai-playground-error": true, children: [
      /* @__PURE__ */ jsx(AlertTitle, { children: t("ai_assistant.playground.loadErrorTitle", "Failed to load AI agents") }),
      /* @__PURE__ */ jsxs(AlertDescription, { children: [
        /* @__PURE__ */ jsx("span", { children: error instanceof Error ? error.message : String(error) }),
        /* @__PURE__ */ jsx("div", { className: "mt-2", children: /* @__PURE__ */ jsxs(
          Button,
          {
            type: "button",
            size: "sm",
            variant: "outline",
            onClick: () => {
              void refetch();
            },
            children: [
              /* @__PURE__ */ jsx(RefreshCcw, { className: "size-4", "aria-hidden": true }),
              /* @__PURE__ */ jsx("span", { children: t("ai_assistant.playground.retry", "Retry") })
            ]
          }
        ) })
      ] })
    ] });
  }
  if (!agents.length) {
    return /* @__PURE__ */ jsx(PlaygroundNoAgents, {});
  }
  return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-4", "data-ai-playground": true, children: [
    /* @__PURE__ */ jsxs("header", { className: "flex flex-col gap-1", children: [
      /* @__PURE__ */ jsx("h1", { className: "text-2xl font-bold tracking-tight", children: t("ai_assistant.playground.title", "AI Playground") }),
      /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t(
        "ai_assistant.playground.subtitle",
        "Exercise every registered AI agent end-to-end. Use the debug panel to inspect request and response payloads, and the object-mode tab to preview structured output."
      ) })
    ] }),
    /* @__PURE__ */ jsxs("section", { className: "flex flex-col gap-3 rounded-lg border border-border bg-background p-3", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2 sm:flex-1", children: [
          /* @__PURE__ */ jsx(Label, { htmlFor: "ai-playground-agent-picker", children: t("ai_assistant.playground.agentPickerLabel", "Agent") }),
          /* @__PURE__ */ jsx(
            "select",
            {
              id: "ai-playground-agent-picker",
              "data-ai-playground-agent-picker": true,
              className: "h-9 rounded-md border border-input bg-background px-3 text-sm",
              value: selectedAgentId ?? "",
              onChange: (event) => setSelectedAgentId(event.target.value),
              children: agents.map((agent) => /* @__PURE__ */ jsxs("option", { value: agent.id, children: [
                agent.label,
                " (",
                agent.id,
                ")"
              ] }, agent.id))
            }
          )
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3 sm:flex-shrink-0", children: [
          /* @__PURE__ */ jsx(Label, { htmlFor: "ai-playground-debug", className: "text-sm", children: t("ai_assistant.playground.debugToggle", "Debug panel") }),
          /* @__PURE__ */ jsx(
            Switch,
            {
              id: "ai-playground-debug",
              checked: debugEnabled,
              onCheckedChange: (next) => setDebugEnabled(next),
              "aria-label": t("ai_assistant.playground.debugToggle", "Debug panel"),
              "data-ai-playground-debug-toggle": true
            }
          ),
          /* @__PURE__ */ jsx(
            IconButton,
            {
              type: "button",
              variant: "ghost",
              size: "sm",
              onClick: () => {
                void refetch();
              },
              "aria-label": t("ai_assistant.playground.refresh", "Refresh agents"),
              disabled: isFetching,
              children: /* @__PURE__ */ jsx(RefreshCcw, { className: "size-4", "aria-hidden": true })
            }
          )
        ] })
      ] }),
      selectedAgent ? /* @__PURE__ */ jsx(AgentDetails, { agent: selectedAgent }) : null,
      selectedAgent ? /* @__PURE__ */ jsx(ModelResolutionPanel, { agentId: selectedAgent.id }) : null,
      selectedAgent ? /* @__PURE__ */ jsx(LoopDisabledPlaygroundBanner, { agentId: selectedAgent.id }) : null
    ] }),
    selectedAgent ? /* @__PURE__ */ jsxs(
      Tabs,
      {
        value: tab,
        onValueChange: (next) => setTab(next === "object" ? "object" : "chat"),
        children: [
          /* @__PURE__ */ jsxs(TabsList, { children: [
            /* @__PURE__ */ jsx(TabsTrigger, { value: "chat", children: t("ai_assistant.playground.tabs.chat", "Chat") }),
            /* @__PURE__ */ jsx(TabsTrigger, { value: "object", children: t("ai_assistant.playground.tabs.object", "Object mode") })
          ] }),
          /* @__PURE__ */ jsx(TabsContent, { value: "chat", children: /* @__PURE__ */ jsx(ChatLane, { agent: selectedAgent, debug: debugEnabled }) }),
          /* @__PURE__ */ jsx(TabsContent, { value: "object", children: /* @__PURE__ */ jsx(ObjectLane, { agent: selectedAgent }) })
        ]
      }
    ) : null
  ] });
}
var AiPlaygroundPageClient_default = AiPlaygroundPageClient;
export {
  AiPlaygroundPageClient,
  AiPlaygroundPageClient_default as default
};
//# sourceMappingURL=AiPlaygroundPageClient.js.map
