import { jsx, jsxs } from "react/jsx-runtime";
import { renderToString } from "react-dom/server";
import { useQueryClient, useQuery, useMutation, QueryClientProvider, QueryClient } from "@tanstack/react-query";
import React, { useState, useMemo } from "react";
import { App as App$1, Layout, Typography, Space, Button, Menu, Badge, Card, Form, Input, Alert, Table, Tag, Descriptions } from "antd";
const defaultProxyBaseUrl = "http://127.0.0.1:8080";
function App() {
  const [tab, setTab] = useState("agents");
  const tabs = [
    ["agents", "Agents"],
    ["events", "Events"],
    ["tasks", "Tasks"],
    ["inventory", "Inventory"],
    ["plans", "Plans"],
    ["proxy", "Proxy"],
    ["notifications", "Notifications"],
    ["doctor", "Doctor"]
  ];
  return /* @__PURE__ */ jsx(App$1, { children: /* @__PURE__ */ jsxs(Layout, { className: "appShell", children: [
    /* @__PURE__ */ jsxs(Layout.Header, { className: "appHeader", children: [
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx(Typography.Text, { type: "secondary", children: "Local-first AI agent event center" }),
        /* @__PURE__ */ jsx(Typography.Title, { level: 1, children: "AgentPulse" })
      ] }),
      /* @__PURE__ */ jsxs(Space, { size: "middle", wrap: true, children: [
        /* @__PURE__ */ jsx(Button, { href: "/docs/", target: "_blank", children: "使用文档" }),
        /* @__PURE__ */ jsx(HealthBadge, {})
      ] })
    ] }),
    /* @__PURE__ */ jsxs(Layout.Content, { className: "appContent", children: [
      /* @__PURE__ */ jsx(Menu, { mode: "horizontal", selectedKeys: [tab], items: tabs.map(([key, label]) => ({ key, label })), onClick: ({ key }) => setTab(key) }),
      /* @__PURE__ */ jsxs("section", { className: "pageContent", children: [
        tab === "agents" && /* @__PURE__ */ jsx(Agents, {}),
        tab === "events" && /* @__PURE__ */ jsx(Events, {}),
        tab === "tasks" && /* @__PURE__ */ jsx(Tasks, {}),
        tab === "inventory" && /* @__PURE__ */ jsx(Inventory, {}),
        tab === "plans" && /* @__PURE__ */ jsx(Plans, {}),
        tab === "proxy" && /* @__PURE__ */ jsx(ProxyRequests, {}),
        tab === "notifications" && /* @__PURE__ */ jsx(Notifications, {}),
        tab === "doctor" && /* @__PURE__ */ jsx(Doctor, {})
      ] })
    ] })
  ] }) });
}
function HealthBadge() {
  const { data, isError } = useApi("/api/health");
  return /* @__PURE__ */ jsx(Badge, { status: isError ? "error" : data ? "success" : "processing", text: isError ? "offline" : data ? "online" : "checking" });
}
function Agents() {
  const queryClient = useQueryClient();
  const { message, modal } = App$1.useApp();
  const [proxyBaseUrl, setProxyBaseUrl] = useState(defaultProxyBaseUrl);
  const [rowMessage, setRowMessage] = useState({});
  const { data, isFetching } = useQuery({
    queryKey: ["/api/agents/scan", proxyBaseUrl],
    queryFn: () => postJson("/api/agents/scan", { scope: "user", proxyBaseUrl }),
    staleTime: 0
  });
  const rows = Array.isArray(data) ? data : [];
  const scan = useMutation({
    mutationFn: () => postJson("/api/agents/scan", { scope: "user", proxyBaseUrl }),
    onSuccess: async () => {
      await queryClient.invalidateQueries({ queryKey: ["/api/agents/scan"] });
      message.success("扫描完成");
    }
  });
  const replace = useMutation({
    mutationFn: (row) => postJson(`/api/agents/${row.integration}/replace`, { scope: "user", proxyBaseUrl, yes: true }),
    onSuccess: async (result, row) => {
      setRowMessage((current) => {
        var _a, _b;
        return { ...current, [row.integration]: result.ok ? "替换完成，配置已验证。" : `替换失败：${result.error || ((_b = (_a = result.result) == null ? void 0 : _a.warnings) == null ? void 0 : _b.join("；")) || "请查看详情"}` };
      });
      await refreshAgentViews(queryClient);
    }
  });
  const rollback = useMutation({
    mutationFn: (integration) => postJson(`/api/agents/${integration}/rollback`, {}),
    onSuccess: async (result, integration) => {
      setRowMessage((current) => {
        var _a, _b;
        return { ...current, [integration]: result.ok ? "回滚完成。" : `回滚失败：${result.error || ((_b = (_a = result.result) == null ? void 0 : _a.warnings) == null ? void 0 : _b.join("；")) || "没有可用备份"}` };
      });
      await refreshAgentViews(queryClient);
    }
  });
  const columns = [
    {
      title: "Agent",
      dataIndex: "integration",
      key: "integration",
      width: 150,
      render: (value) => /* @__PURE__ */ jsx(Typography.Text, { strong: true, children: value })
    },
    {
      title: "检测状态",
      key: "detected",
      width: 110,
      render: (_, row) => /* @__PURE__ */ jsx(Tag, { color: row.detected ? "green" : "default", children: row.detected ? "已发现" : "未发现" })
    },
    {
      title: "路由状态",
      key: "routed",
      width: 120,
      render: (_, row) => {
        var _a, _b;
        return /* @__PURE__ */ jsx(Tag, { color: ((_a = row.routeState) == null ? void 0 : _a.routed) ? "blue" : row.routeState ? "orange" : "default", children: ((_b = row.routeState) == null ? void 0 : _b.routed) ? "已代理" : row.routeState ? "未代理" : "未识别" });
      }
    },
    {
      title: "用户级目标文件",
      key: "configPath",
      ellipsis: true,
      render: (_, row) => {
        var _a;
        return row.targetConfigPath || ((_a = row.routeState) == null ? void 0 : _a.configPath) || "-";
      }
    },
    {
      title: "原始上游",
      key: "currentBaseUrl",
      ellipsis: true,
      render: (_, row) => {
        var _a;
        return row.originalUpstream || ((_a = row.routeState) == null ? void 0 : _a.currentBaseUrl) || "-";
      }
    },
    {
      title: "提示",
      key: "warnings",
      render: (_, row) => {
        var _a, _b, _c, _d;
        const text = rowMessage[row.integration] || ((_a = row.warnings) == null ? void 0 : _a.join("；")) || ((_c = (_b = row.routeState) == null ? void 0 : _b.warnings) == null ? void 0 : _c.join("；")) || "-";
        return /* @__PURE__ */ jsx(Typography.Text, { type: rowMessage[row.integration] ? "success" : ((_d = row.warnings) == null ? void 0 : _d.length) ? "warning" : "secondary", children: text });
      }
    },
    {
      title: "操作",
      key: "actions",
      width: 190,
      render: (_, row) => {
        var _a;
        return /* @__PURE__ */ jsxs(Space, { children: [
          /* @__PURE__ */ jsx(Button, { type: "primary", disabled: !row.canReplace, loading: replace.isPending && ((_a = replace.variables) == null ? void 0 : _a.integration) === row.integration, onClick: () => confirmReplace(row), children: "替换" }),
          /* @__PURE__ */ jsx(Button, { disabled: !row.canRollback, loading: rollback.isPending && rollback.variables === row.integration, onClick: () => rollback.mutate(row.integration), children: row.canRollback ? "回滚" : "无备份" })
        ] });
      }
    }
  ];
  const confirmReplace = (row) => {
    modal.confirm({
      title: `确认替换 ${row.integration} 用户级配置？`,
      okText: "确认替换",
      cancelText: "取消",
      content: /* @__PURE__ */ jsxs("div", { className: "confirmBody", children: [
        /* @__PURE__ */ jsxs(Descriptions, { size: "small", column: 1, bordered: false, children: [
          /* @__PURE__ */ jsx(Descriptions.Item, { label: "目标配置文件", children: row.targetConfigPath || "-" }),
          /* @__PURE__ */ jsx(Descriptions.Item, { label: "原始上游", children: row.originalUpstream || "未配置，按官方上游处理" }),
          /* @__PURE__ */ jsx(Descriptions.Item, { label: "新代理地址", children: row.proxyBaseUrl || `${proxyBaseUrl.replace(/\/+$/, "")}/proxy/${row.integration}` }),
          /* @__PURE__ */ jsx(Descriptions.Item, { label: "文件状态", children: row.willCreateConfig ? "将创建配置文件" : "将修改现有配置文件" })
        ] }),
        /* @__PURE__ */ jsx(Typography.Paragraph, { type: "secondary", className: "confirmNote", children: "操作前会自动备份，可在该 Agent 行点击“回滚”恢复原配置；回滚也会删除对应代理映射。" })
      ] }),
      onOk: () => replace.mutateAsync(row)
    });
  };
  return /* @__PURE__ */ jsxs(
    Card,
    {
      title: "Agent 代理配置",
      extra: /* @__PURE__ */ jsx(Button, { type: "primary", loading: scan.isPending || isFetching, onClick: () => scan.mutate(), children: "扫描" }),
      children: [
        /* @__PURE__ */ jsxs(Form, { layout: "inline", className: "agentToolbar", children: [
          /* @__PURE__ */ jsx(Form.Item, { label: "配置范围", children: /* @__PURE__ */ jsx(Typography.Text, { children: "用户级配置" }) }),
          /* @__PURE__ */ jsx(Form.Item, { label: "代理地址", children: /* @__PURE__ */ jsx(Input, { value: proxyBaseUrl, onChange: (event) => setProxyBaseUrl(event.target.value), className: "proxyInput" }) })
        ] }),
        /* @__PURE__ */ jsx(Alert, { type: "info", showIcon: true, message: "当前页面直接操作当前用户目录下的真实 Agent 配置文件；点击替换前会展示确认弹窗，并在写入前自动备份。", className: "agentAlert" }),
        /* @__PURE__ */ jsx(Table, { rowKey: "integration", columns, dataSource: rows, loading: scan.isPending || isFetching, pagination: false, scroll: { x: 1100 } })
      ]
    }
  );
}
function Events() {
  const { data } = useApi("/api/events");
  const rows = Array.isArray(data) ? data : [];
  return /* @__PURE__ */ jsx(Card, { title: "Event Stream", extra: /* @__PURE__ */ jsx(CurlHint, {}), children: rows.length ? /* @__PURE__ */ jsx(JsonRows, { rows }) : /* @__PURE__ */ jsx(Empty, { text: "No events yet. Send a hook event to begin." }) });
}
function Tasks() {
  const { data: tasks } = useApi("/api/tasks");
  const { data: sessions } = useApi("/api/sessions");
  return /* @__PURE__ */ jsxs("div", { className: "grid", children: [
    /* @__PURE__ */ jsx(Card, { title: "Tasks", children: Array.isArray(tasks) && tasks.length ? /* @__PURE__ */ jsx(JsonRows, { rows: tasks }) : /* @__PURE__ */ jsx(Empty, { text: "No tasks yet." }) }),
    /* @__PURE__ */ jsx(Card, { title: "Sessions", children: Array.isArray(sessions) && sessions.length ? /* @__PURE__ */ jsx(JsonRows, { rows: sessions }) : /* @__PURE__ */ jsx(Empty, { text: "No sessions yet." }) })
  ] });
}
function Inventory() {
  var _a, _b, _c;
  const queryClient = useQueryClient();
  const { data } = useApi("/api/inventory");
  const scan = useMutation({
    mutationFn: () => fetch("/api/inventory/scan", { method: "POST" }).then((response) => response.json()),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ["/api/inventory"] })
  });
  const snapshot = data || {};
  return /* @__PURE__ */ jsxs("div", { className: "stack", children: [
    /* @__PURE__ */ jsx(Button, { type: "primary", onClick: () => scan.mutate(), loading: scan.isPending, children: "Scan Inventory" }),
    /* @__PURE__ */ jsxs("div", { className: "grid three", children: [
      /* @__PURE__ */ jsx(Card, { title: `Sources (${((_a = snapshot.sources) == null ? void 0 : _a.length) || 0})`, children: /* @__PURE__ */ jsx(JsonRows, { rows: snapshot.sources || [] }) }),
      /* @__PURE__ */ jsx(Card, { title: `Skills (${((_b = snapshot.skills) == null ? void 0 : _b.length) || 0})`, children: /* @__PURE__ */ jsx(JsonRows, { rows: snapshot.skills || [] }) }),
      /* @__PURE__ */ jsx(Card, { title: `MCP Servers (${((_c = snapshot.mcpServers) == null ? void 0 : _c.length) || 0})`, children: /* @__PURE__ */ jsx(JsonRows, { rows: snapshot.mcpServers || [] }) })
    ] })
  ] });
}
function Plans() {
  const queryClient = useQueryClient();
  const { data } = useApi("/api/install/plans");
  const createPlan = useMutation({
    mutationFn: () => fetch("/api/install/plan", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ scope: "workspace" }) }).then((response) => response.json()),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ["/api/install/plans"] })
  });
  return /* @__PURE__ */ jsx(Card, { title: "Install Plans", extra: /* @__PURE__ */ jsx(Button, { type: "primary", onClick: () => createPlan.mutate(), loading: createPlan.isPending, children: "Create Workspace Plan" }), children: Array.isArray(data) && data.length ? /* @__PURE__ */ jsx(JsonRows, { rows: data }) : /* @__PURE__ */ jsx(Empty, { text: "No install plans yet." }) });
}
function ProxyRequests() {
  const { data } = useApi("/api/proxy/requests");
  const rows = Array.isArray(data) ? data : [];
  const columns = [
    { title: "Provider", dataIndex: "provider", key: "provider", width: 120 },
    { title: "Proxy Key", key: "proxyKey", width: 140, render: (_, row) => row.proxyKey || "-" },
    { title: "API 标准", key: "apiProtocol", width: 180, render: (_, row) => row.apiProtocol || "-" },
    { title: "Method", dataIndex: "method", key: "method", width: 100 },
    { title: "Path", dataIndex: "path", key: "path", ellipsis: true },
    {
      title: "Status",
      key: "status",
      width: 110,
      render: (_, row) => {
        if (!row.statusCode) return /* @__PURE__ */ jsx(Tag, { color: row.error ? "red" : "default", children: "-" });
        const color = row.statusCode >= 500 ? "red" : row.statusCode >= 400 ? "orange" : "green";
        return /* @__PURE__ */ jsx(Tag, { color, children: row.statusCode });
      }
    },
    { title: "Duration", key: "duration", width: 120, render: (_, row) => row.durationMs == null ? "-" : `${row.durationMs} ms` },
    { title: "Error", key: "error", ellipsis: true, render: (_, row) => row.error ? /* @__PURE__ */ jsx(Typography.Text, { type: "danger", children: row.error }) : "-" },
    { title: "Created", dataIndex: "createdAt", key: "createdAt", width: 220 }
  ];
  return /* @__PURE__ */ jsxs(Card, { title: "Proxy Requests", children: [
    /* @__PURE__ */ jsx(Table, { rowKey: "id", columns, dataSource: rows, pagination: false, scroll: { x: 1200 } }),
    !rows.length && /* @__PURE__ */ jsx("div", { className: "tableEmpty", children: /* @__PURE__ */ jsx(Empty, { text: "No proxy traffic captured yet." }) })
  ] });
}
function Notifications() {
  const test = useMutation({
    mutationFn: (channel) => fetch("/api/notifications/test", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ channel }) }).then((response) => response.json())
  });
  return /* @__PURE__ */ jsxs(Card, { title: "Notification Test", children: [
    /* @__PURE__ */ jsxs(Space, { children: [
      /* @__PURE__ */ jsx(Button, { onClick: () => test.mutate("webhook"), children: "Test Webhook" }),
      /* @__PURE__ */ jsx(Button, { onClick: () => test.mutate("windows"), children: "Test Windows" })
    ] }),
    test.data ? /* @__PURE__ */ jsx("pre", { children: JSON.stringify(test.data, null, 2) }) : /* @__PURE__ */ jsx(Empty, { text: "Choose a channel to test." })
  ] });
}
function Doctor() {
  const { data: health } = useApi("/api/health");
  const { data: scan } = useApi("/api/scan");
  const summary = useMemo(() => ({ health, scan }), [health, scan]);
  return /* @__PURE__ */ jsx(Card, { title: "Doctor", children: /* @__PURE__ */ jsx("pre", { children: JSON.stringify(summary, null, 2) }) });
}
function JsonRows({ rows }) {
  if (!rows.length) return /* @__PURE__ */ jsx(Empty, { text: "Nothing to show." });
  return /* @__PURE__ */ jsx("pre", { children: JSON.stringify(rows, null, 2) });
}
function Empty({ text }) {
  return /* @__PURE__ */ jsx(Typography.Text, { type: "secondary", children: text });
}
function CurlHint() {
  return /* @__PURE__ */ jsx(Typography.Text, { code: true, children: "curl -X POST /ingest/hook/codex/session.start" });
}
function useApi(path) {
  return useQuery({
    queryKey: [path],
    queryFn: async () => {
      const response = await fetch(path);
      if (!response.ok) throw new Error(`${response.status}`);
      return response.json();
    },
    refetchInterval: path.includes("events") || path.includes("tasks") ? 3e3 : false
  });
}
async function postJson(path, body) {
  const response = await fetch(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
  if (!response.ok) throw new Error(`${response.status}`);
  return response.json();
}
async function refreshAgentViews(queryClient) {
  await Promise.all([
    queryClient.invalidateQueries({ queryKey: ["/api/agents/scan"] }),
    queryClient.invalidateQueries({ queryKey: ["/api/install/plans"] }),
    queryClient.invalidateQueries({ queryKey: ["/api/proxy/requests"] })
  ]);
}
function Root({ queryClient }) {
  return /* @__PURE__ */ jsx(React.StrictMode, { children: /* @__PURE__ */ jsx(QueryClientProvider, { client: queryClient, children: /* @__PURE__ */ jsx(App, {}) }) });
}
function render(_url) {
  return renderToString(/* @__PURE__ */ jsx(Root, { queryClient: new QueryClient() }));
}
export {
  render
};
