import { Button, Input, Picker, ScrollView, Switch, Text, Textarea, View } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import { useCallback, useMemo, useState } from "react";
import AdminGuard from "../../components/AdminGuard";
import {
  AgentCapability,
  AgentConversation,
  AgentConversationCompactResult,
  AgentConversationContextPreview,
  AgentCurrentPrompt,
  AgentEvalComparisonRow,
  AgentEvalRun,
  AgentOpsAlert,
  AgentOpsAlertCheckResult,
  AgentOpsOverview,
  AgentPromptRolloutMonitorResult,
  AgentPromptVersion,
  AgentReadiness,
  activateAgentPromptVersion,
  archiveAgentPromptVersion,
  bootstrapOfficialSession,
  checkAgentOpsAlerts,
  checkAgentPromptQualityGate,
  compactAgentConversation,
  createAgentPromptVersion,
  createConversation,
  getAgentEvalComparison,
  getAgentCurrentPrompt,
  getAgentEvalSummary,
  getAgentOpsOverview,
  getAgentReadiness,
  getAgentSessionToken,
  getGroupedCapabilities,
  listConversations,
  listAgentEvalRuns,
  listAgentOpsAlerts,
  listAgentPromptVersions,
  monitorAgentPromptRollouts,
  previewAgentConversationContext,
  runAgentEval,
} from "../../api/agent";
import "./index.scss";

type Row = Record<string, unknown>;

const DEFAULT_MODEL = "qwen-turbo";

function compactToken(token: string) {
  if (!token) return "未建立";
  if (token.length <= 18) return token;
  return `${token.slice(0, 8)}...${token.slice(-6)}`;
}

function asRows(value: unknown): Row[] {
  return Array.isArray(value) ? (value as Row[]) : [];
}

function asText(value: unknown, fallback = "-") {
  if (value === null || value === undefined) return fallback;
  const text = String(value).trim();
  return text || fallback;
}

function firstValue(row: Row, keys: string[]) {
  for (const key of keys) {
    const value = row[key];
    if (value !== null && value !== undefined && String(value).trim()) {
      return value;
    }
  }
  return "";
}

function formatJson(value: unknown, maxLength = 1200) {
  if (value === null || value === undefined) return "-";
  let text = "";
  if (typeof value === "string") {
    text = value;
  } else {
    try {
      text = JSON.stringify(value, null, 2);
    } catch {
      text = String(value);
    }
  }
  return text.length > maxLength ? `${text.slice(0, maxLength)}...` : text;
}

function Metric({ label, value }: { label: string; value: unknown }) {
  return (
    <View className="agent-debug-metric">
      <Text className="agent-debug-metric__value">{asText(value, "0")}</Text>
      <Text className="agent-debug-metric__label">{label}</Text>
    </View>
  );
}

function ResultRows({ title, rows }: { title: string; rows?: Row[] }) {
  const items = asRows(rows).slice(0, 6);
  return (
    <View className="agent-debug-result">
      <View className="agent-debug-result__head">
        <Text className="agent-debug-result__title">{title}</Text>
        <Text className="agent-debug-result__count">{asRows(rows).length}</Text>
      </View>
      {items.length ? (
        items.map((row, index) => {
          const titleText = asText(firstValue(row, [
            "title",
            "promptVersion",
            "promptCode",
            "caseCode",
            "runCode",
            "summaryText",
            "memoryText",
            "action",
            "actionCode",
            "content",
            "messagePreview",
            "chunkText",
            "chunk_text",
            "id",
          ]), `#${index + 1}`);
          const metaText = asText(firstValue(row, [
            "role",
            "modelCode",
            "memoryType",
            "memory_type",
            "retrievalSource",
            "retrieval_source",
            "executionMode",
            "module",
            "moduleCode",
            "riskLevel",
            "status",
            "severity",
            "rating",
            "verdict",
            "sourceType",
            "source_type",
          ]), "");
          const bodyText = asText(firstValue(row, [
            "snippet",
            "detail",
            "summaryText",
            "memoryText",
            "content",
            "messagePreview",
            "replyPreview",
            "avgScore",
            "failedCases",
            "runCount",
            "gateReason",
            "description",
            "blockedReasons",
            "requiredFields",
            "newRolloutMode",
            "score",
            "chunkText",
            "chunk_text",
            "resultSummary",
            "result_summary",
          ]), "");
          return (
            <View key={`${title}-${index}`} className="agent-debug-row">
              <View className="agent-debug-row__top">
                <Text className="agent-debug-row__title">{titleText}</Text>
                {metaText ? <Text className="agent-debug-row__tag">{metaText}</Text> : null}
              </View>
              {bodyText && bodyText !== titleText ? (
                <Text className="agent-debug-row__body" selectable>
                  {bodyText}
                </Text>
              ) : (
                <Text className="agent-debug-row__body" selectable>
                  {formatJson(row, 520)}
                </Text>
              )}
            </View>
          );
        })
      ) : (
        <Text className="agent-debug-result__empty">0</Text>
      )}
    </View>
  );
}

export default function AdminAgentDebugPage() {
  const [sessionToken, setSessionToken] = useState(() => String(getAgentSessionToken() || ""));
  const [conversations, setConversations] = useState<AgentConversation[]>([]);
  const [conversationId, setConversationId] = useState(0);
  const [manualConversationId, setManualConversationId] = useState("");
  const [query, setQuery] = useState("");
  const [includePromptBlock, setIncludePromptBlock] = useState(false);
  const [model, setModel] = useState(DEFAULT_MODEL);
  const [extractMemories, setExtractMemories] = useState(true);
  const [preview, setPreview] = useState<AgentConversationContextPreview | null>(null);
  const [compactResult, setCompactResult] = useState<AgentConversationCompactResult | null>(null);
  const [evalSummary, setEvalSummary] = useState<Record<string, unknown> | null>(null);
  const [evalRuns, setEvalRuns] = useState<AgentEvalRun[]>([]);
  const [evalComparison, setEvalComparison] = useState<AgentEvalComparisonRow[]>([]);
  const [evalResult, setEvalResult] = useState<AgentEvalRun | null>(null);
  const [opsOverview, setOpsOverview] = useState<AgentOpsOverview | null>(null);
  const [opsAlerts, setOpsAlerts] = useState<AgentOpsAlert[]>([]);
  const [opsAlertResult, setOpsAlertResult] = useState<AgentOpsAlertCheckResult | null>(null);
  const [readiness, setReadiness] = useState<AgentReadiness | null>(null);
  const [capabilityGroups, setCapabilityGroups] = useState<Record<string, AgentCapability[]>>({});
  const [promptCurrent, setPromptCurrent] = useState<AgentCurrentPrompt | null>(null);
  const [promptVersions, setPromptVersions] = useState<AgentPromptVersion[]>([]);
  const [promptDraftVersion, setPromptDraftVersion] = useState("");
  const [promptDraftTitle, setPromptDraftTitle] = useState("连小新官方聊天主提示词");
  const [promptDraftBody, setPromptDraftBody] = useState("");
  const [promptRolloutMode, setPromptRolloutMode] = useState("full");
  const [promptRolloutPercent, setPromptRolloutPercent] = useState("100");
  const [promptMonitorResult, setPromptMonitorResult] = useState<AgentPromptRolloutMonitorResult | null>(null);
  const [loadingKey, setLoadingKey] = useState("");

  const selectedIndex = useMemo(() => {
    const index = conversations.findIndex((item) => item.id === conversationId);
    return index >= 0 ? index : 0;
  }, [conversationId, conversations]);

  const conversationLabels = useMemo(
    () => conversations.map((item) => `${item.title || "未命名会话"} #${item.id}`),
    [conversations]
  );

  const selectedConversation = conversations.find((item) => item.id === conversationId);
  const opsHealth = (opsOverview?.health || {}) as NonNullable<AgentOpsOverview["health"]>;
  const opsChat = (opsOverview?.chat || {}) as Row;
  const opsFeedback = (opsOverview?.feedback || {}) as Row;
  const opsEval = (opsOverview?.eval || {}) as Row;
  const opsPrompt = (opsOverview?.prompt || {}) as Row;
  const opsRollout = (opsOverview?.rollout || {}) as Row;
  const opsMemory = (opsOverview?.memory || {}) as Row;
  const opsKnowledge = (opsOverview?.knowledge || {}) as Row;
  const opsAction = (opsOverview?.action || {}) as Row;
  const readinessTotals = (readiness?.totals || {}) as Row;
  const capabilityRows = useMemo(
    () => Object.values(capabilityGroups).reduce<AgentCapability[]>(
      (items, groupRows) => items.concat(Array.isArray(groupRows) ? groupRows : []),
      []
    ),
    [capabilityGroups]
  );
  const availableCapabilityRows = useMemo(
    () => capabilityRows.filter((item) => item.available !== false),
    [capabilityRows]
  );
  const blockedCapabilityRows = useMemo(
    () => capabilityRows.filter((item) => item.available === false),
    [capabilityRows]
  );
  const runtimeCapabilityRows = useMemo(
    () => capabilityRows.filter((item) => item.runtimeOwned),
    [capabilityRows]
  );
  const p3CapabilityRows = useMemo(
    () => capabilityRows.filter((item) => {
      const code = item.actionCode || item.toolName || "";
      return code.startsWith("mutual_aid.") || code.startsWith("service_team.") || code.startsWith("service_project.");
    }),
    [capabilityRows]
  );

  const refreshEvalDashboard = useCallback(async () => {
    const [summary, runs, comparison] = await Promise.all([
      getAgentEvalSummary(),
      listAgentEvalRuns(5),
      getAgentEvalComparison({ promptCode: "official_chat", days: 30, limit: 6 }),
    ]);
    setEvalSummary(summary);
    setEvalRuns(runs);
    setEvalComparison(comparison);
  }, []);

  const refreshOpsDashboard = useCallback(async () => {
    const [overview, alerts, readinessResult] = await Promise.all([
      getAgentOpsOverview(),
      listAgentOpsAlerts({ status: "open", limit: 8 }),
      getAgentReadiness(),
    ]);
    setOpsOverview(overview);
    setOpsAlerts(alerts);
    setReadiness(readinessResult);
  }, []);

  const refreshCapabilityDashboard = useCallback(async () => {
    const data = await getGroupedCapabilities();
    setCapabilityGroups(data?.groups || {});
  }, []);

  const refreshPromptDashboard = useCallback(async () => {
    const [current, versions] = await Promise.all([
      getAgentCurrentPrompt({ model: model.trim() || undefined }),
      listAgentPromptVersions({ limit: 6 }),
    ]);
    setPromptCurrent(current);
    setPromptVersions(versions);
    setPromptDraftTitle((text) => text || current.title || "连小新官方聊天主提示词");
    setPromptDraftBody((text) => text || current.systemPrompt || "");
  }, [model]);

  const ensureSession = useCallback(async () => {
    const current = String(getAgentSessionToken() || "");
    if (current) {
      setSessionToken(current);
      return current;
    }
    const result = await bootstrapOfficialSession();
    const token = String(result?.sessionToken || getAgentSessionToken() || "");
    setSessionToken(token);
    return token;
  }, []);

  const refreshConversations = useCallback(async () => {
    const rows = await listConversations();
    setConversations(rows);
    setConversationId((current) => {
      if (current && rows.some((item) => item.id === current)) return current;
      return rows[0]?.id || 0;
    });
    if (rows[0]?.id && !manualConversationId) {
      setManualConversationId(String(rows[0].id));
    }
    return rows;
  }, [manualConversationId]);

  const initialize = useCallback(async () => {
    setLoadingKey("init");
    try {
      try {
        await ensureSession();
        await refreshConversations();
      } catch {
        setSessionToken("");
        setConversations([]);
        setConversationId(0);
        setManualConversationId("");
      }
      try {
        await refreshOpsDashboard();
      } catch {
        // Ops dashboard is optional for older deployments or non-admin accounts.
      }
      try {
        await refreshCapabilityDashboard();
      } catch {
        // Capability metadata is optional for older deployments.
      }
      try {
        await refreshEvalDashboard();
      } catch {
        // Eval dashboard is optional for older deployments or non-admin accounts.
      }
      try {
        await refreshPromptDashboard();
      } catch {
        // Prompt versioning is optional for older deployments or non-admin accounts.
      }
    } catch (e) {
      Taro.showToast({ title: e instanceof Error ? e.message : "初始化失败", icon: "none" });
    } finally {
      setLoadingKey("");
    }
  }, [ensureSession, refreshCapabilityDashboard, refreshConversations, refreshEvalDashboard, refreshOpsDashboard, refreshPromptDashboard]);

  useDidShow(() => {
    void initialize();
  });

  const resolveConversationId = () => {
    const manualId = Number(manualConversationId);
    if (Number.isFinite(manualId) && manualId > 0) {
      setConversationId(manualId);
      return manualId;
    }
    if (conversationId > 0) return conversationId;
    Taro.showToast({ title: "请输入会话ID", icon: "none" });
    return 0;
  };

  const applyManualConversationId = () => {
    const id = Number(manualConversationId);
    if (!Number.isFinite(id) || id <= 0) {
      Taro.showToast({ title: "请输入会话ID", icon: "none" });
      return 0;
    }
    setConversationId(id);
    return id;
  };

  const createDebugConversation = async () => {
    setLoadingKey("create");
    try {
      await ensureSession();
      const created = await createConversation({
        title: "Agent 调试会话",
        model: model.trim() || DEFAULT_MODEL,
      });
      setConversations((rows) => [created, ...rows.filter((item) => item.id !== created.id)]);
      setConversationId(created.id);
      setManualConversationId(String(created.id));
      setPreview(null);
      setCompactResult(null);
      Taro.showToast({ title: "已创建", icon: "none" });
    } catch (e) {
      Taro.showToast({ title: e instanceof Error ? e.message : "创建失败", icon: "none" });
    } finally {
      setLoadingKey("");
    }
  };

  const runPreview = async () => {
    const id = resolveConversationId();
    if (!id) return;
    setLoadingKey("preview");
    try {
      await ensureSession();
      const data = await previewAgentConversationContext(id, {
        query: query.trim(),
        includePromptBlock,
      });
      setPreview(data);
      setManualConversationId(String(id));
    } catch (e) {
      Taro.showToast({ title: e instanceof Error ? e.message : "Preview失败", icon: "none" });
    } finally {
      setLoadingKey("");
    }
  };

  const runCompact = async () => {
    const id = resolveConversationId();
    if (!id) return;
    setLoadingKey("compact");
    try {
      await ensureSession();
      const data = await compactAgentConversation(id, {
        model: model.trim() || undefined,
        extractMemories,
      });
      setCompactResult(data);
      await refreshConversations();
      Taro.showToast({ title: "Compact完成", icon: "none" });
    } catch (e) {
      Taro.showToast({ title: e instanceof Error ? e.message : "Compact失败", icon: "none" });
    } finally {
      setLoadingKey("");
    }
  };

  const runEval = async () => {
    setLoadingKey("eval");
    try {
      const data = await runAgentEval({
        model: model.trim() || undefined,
        limit: 8,
      });
      setEvalResult(data);
      await Promise.all([refreshEvalDashboard(), refreshOpsDashboard()]);
      Taro.showToast({ title: "Eval完成", icon: "none" });
    } catch (e) {
      Taro.showToast({ title: e instanceof Error ? e.message : "Eval失败", icon: "none" });
    } finally {
      setLoadingKey("");
    }
  };

  const refreshOpsOnly = async () => {
    setLoadingKey("ops");
    try {
      await Promise.all([refreshOpsDashboard(), refreshCapabilityDashboard()]);
      Taro.showToast({ title: "Ops已刷新", icon: "none" });
    } catch (e) {
      Taro.showToast({ title: e instanceof Error ? e.message : "Ops刷新失败", icon: "none" });
    } finally {
      setLoadingKey("");
    }
  };

  const runOpsAlertCheck = async () => {
    setLoadingKey("ops-alerts");
    try {
      const data = await checkAgentOpsAlerts({
        notifyAdmins: true,
        resolveHealthy: true,
        minimumNotifySeverity: "critical",
      });
      setOpsAlertResult(data);
      await refreshOpsDashboard();
      Taro.showToast({ title: "告警检查完成", icon: "none" });
    } catch (e) {
      Taro.showToast({ title: e instanceof Error ? e.message : "告警检查失败", icon: "none" });
    } finally {
      setLoadingKey("");
    }
  };

  const savePromptDraft = async () => {
    const body = promptDraftBody.trim();
    if (!body) {
      Taro.showToast({ title: "请输入Prompt内容", icon: "none" });
      return;
    }
    setLoadingKey("prompt-save");
    try {
      const percent = Number(promptRolloutPercent);
      await createAgentPromptVersion({
        promptCode: "official_chat",
        version: promptDraftVersion.trim() || `manual-${Date.now()}`,
        title: promptDraftTitle.trim() || "连小新官方聊天主提示词",
        systemPrompt: body,
        modelCode: model.trim() || undefined,
        rolloutMode: promptRolloutMode,
        rolloutPercent: Number.isFinite(percent) ? Math.max(0, Math.min(100, percent)) : 100,
        metadata: { createdFrom: "admin-agent-debug" },
      });
      setPromptDraftVersion("");
      await Promise.all([refreshPromptDashboard(), refreshOpsDashboard()]);
      Taro.showToast({ title: "Prompt草稿已保存", icon: "none" });
    } catch (e) {
      Taro.showToast({ title: e instanceof Error ? e.message : "保存失败", icon: "none" });
    } finally {
      setLoadingKey("");
    }
  };

  const activatePrompt = async (item: AgentPromptVersion) => {
    if (!item.id) return;
    setLoadingKey(`prompt-activate-${item.id}`);
    try {
      const percent = Number(promptRolloutPercent);
      await activateAgentPromptVersion(item.id, {
        rolloutMode: promptRolloutMode,
        rolloutPercent: Number.isFinite(percent) ? Math.max(0, Math.min(100, percent)) : 100,
      });
      await Promise.all([refreshPromptDashboard(), refreshOpsDashboard()]);
      Taro.showToast({ title: "Prompt已激活", icon: "none" });
    } catch (e) {
      Taro.showToast({ title: e instanceof Error ? e.message : "激活失败", icon: "none" });
    } finally {
      setLoadingKey("");
    }
  };

  const archivePrompt = async (item: AgentPromptVersion) => {
    if (!item.id) return;
    setLoadingKey(`prompt-archive-${item.id}`);
    try {
      await archiveAgentPromptVersion(item.id);
      await Promise.all([refreshPromptDashboard(), refreshOpsDashboard()]);
      Taro.showToast({ title: "Prompt已归档", icon: "none" });
    } catch (e) {
      Taro.showToast({ title: e instanceof Error ? e.message : "归档失败", icon: "none" });
    } finally {
      setLoadingKey("");
    }
  };

  const checkPromptGate = async (item: AgentPromptVersion) => {
    if (!item.id) return;
    setLoadingKey(`prompt-gate-${item.id}`);
    try {
      await checkAgentPromptQualityGate(item.id);
      await Promise.all([refreshPromptDashboard(), refreshEvalDashboard(), refreshOpsDashboard()]);
      Taro.showToast({ title: "Gate已检查", icon: "none" });
    } catch (e) {
      Taro.showToast({ title: e instanceof Error ? e.message : "检查失败", icon: "none" });
    } finally {
      setLoadingKey("");
    }
  };

  const monitorPromptRollouts = async () => {
    setLoadingKey("prompt-monitor");
    try {
      const data = await monitorAgentPromptRollouts({
        limit: 20,
        minCanaryPercent: 5,
        shrinkStepPercent: 20,
        rollbackFull: true,
      });
      setPromptMonitorResult(data);
      await Promise.all([refreshPromptDashboard(), refreshEvalDashboard(), refreshOpsDashboard()]);
      Taro.showToast({ title: "Monitor完成", icon: "none" });
    } catch (e) {
      Taro.showToast({ title: e instanceof Error ? e.message : "Monitor失败", icon: "none" });
    } finally {
      setLoadingKey("");
    }
  };

  return (
    <AdminGuard>
      <View className="page-shell agent-debug">
        <ScrollView scrollY className="agent-debug__scroll">
          <View className="page-body agent-debug__body">
            <View className="agent-debug__header">
              <View>
                <Text className="agent-debug__title">Agent Runtime</Text>
                <Text className="agent-debug__subtitle">Context / RAG / Memory</Text>
              </View>
              <Button
                className="agent-debug__ghost-button"
                loading={loadingKey === "init"}
                disabled={!!loadingKey}
                onClick={initialize}
              >
                刷新
              </Button>
            </View>

            <View className="agent-debug__panel">
              <View className="agent-debug__status-row">
                <Text className="agent-debug__label">Session</Text>
                <Text className={`agent-debug__status ${sessionToken ? "is-ready" : ""}`}>
                  {compactToken(sessionToken)}
                </Text>
              </View>
              <View className="agent-debug__status-row">
                <Text className="agent-debug__label">会话</Text>
                <Text className="agent-debug__muted">
                  {selectedConversation ? `${selectedConversation.title || "未命名"} #${selectedConversation.id}` : "未选择"}
                </Text>
              </View>

              <Picker
                mode="selector"
                range={conversationLabels}
                value={selectedIndex}
                disabled={!conversationLabels.length || !!loadingKey}
                onChange={(e) => {
                  const index = Number(e.detail.value || 0);
                  const item = conversations[index];
                  if (item?.id) {
                    setConversationId(item.id);
                    setManualConversationId(String(item.id));
                  }
                }}
              >
                <View className="agent-debug__selector">
                  <Text>{conversationLabels[selectedIndex] || "暂无会话"}</Text>
                  <Text className="agent-debug__selector-arrow">›</Text>
                </View>
              </Picker>

              <View className="agent-debug__inline-fields">
                <View className="agent-debug__field agent-debug__field--small">
                  <Text className="agent-debug__field-label">会话ID</Text>
                  <Input
                    className="agent-debug__input"
                    type="number"
                    value={manualConversationId}
                    placeholder="ID"
                    onInput={(e) => setManualConversationId(e.detail.value)}
                    onBlur={() => applyManualConversationId()}
                  />
                </View>
                <View className="agent-debug__field">
                  <Text className="agent-debug__field-label">模型</Text>
                  <Input
                    className="agent-debug__input"
                    value={model}
                    placeholder={DEFAULT_MODEL}
                    onInput={(e) => setModel(e.detail.value)}
                  />
                </View>
              </View>

              <Button
                className="agent-debug__secondary-button"
                loading={loadingKey === "create"}
                disabled={!!loadingKey}
                onClick={createDebugConversation}
              >
                新建调试会话
              </Button>
            </View>

            <View className="agent-debug__panel">
              <View className="agent-debug__panel-head">
                <View>
                  <Text className="agent-debug__panel-title">Ops Dashboard</Text>
                  <Text className="agent-debug__subtitle">{opsOverview?.generatedAt || "未刷新"}</Text>
                </View>
                <Button
                  className="agent-debug__mini-button"
                  loading={loadingKey === "ops"}
                  disabled={!!loadingKey}
                  onClick={refreshOpsOnly}
                >
                  刷新
                </Button>
              </View>
              {opsOverview ? (
                <>
                  <View className="agent-debug__health-line">
                    <Text className={`agent-debug__health-badge is-${opsHealth.status || "unknown"}`}>
                      {asText(opsHealth.status)}
                    </Text>
                    <Text className="agent-debug__hint" selectable>
                      {asText(opsHealth.summary || (opsHealth.reasons || []).join(" / "))}
                    </Text>
                  </View>
                  <View className="agent-debug__metric-grid">
                    <Metric label="Chat24h" value={opsChat.activeConversations24h} />
                    <Metric label="Assist" value={opsChat.assistantCount24h} />
                    <Metric label="Fallback" value={`${asText(opsChat.fallbackRate24h, "0")}%`} />
                    <Metric label="Trim" value={`${asText(opsChat.contextTruncatedRate24h, "0")}%`} />
                    <Metric label="Down" value={`${asText(opsFeedback.downRate30d, "0")}%`} />
                    <Metric label="Eval" value={opsEval.avgScore30d} />
                    <Metric label="GateFail" value={opsPrompt.failedGateCount} />
                    <Metric label="Auto" value={opsRollout.autoActionCount30d} />
                    <Metric label="Pending" value={opsAction.pendingCount} />
                    <Metric label="Memory" value={opsMemory.activeCount} />
                    <Metric label="Knowledge" value={opsKnowledge.activeSourceCount} />
                    <Metric label="K Expired" value={opsKnowledge.expiredActiveCount} />
                    <Metric label="K Soon" value={opsKnowledge.expiringSoonCount} />
                    <Metric label="K Low" value={opsKnowledge.lowTrustActiveCount} />
                    <Metric label="Alerts" value={opsAlerts.length} />
                  </View>
                  <Button
                    className="agent-debug__secondary-button"
                    loading={loadingKey === "ops-alerts"}
                    disabled={!!loadingKey}
                    onClick={runOpsAlertCheck}
                  >
                    Check Alerts
                  </Button>
                  {opsAlertResult ? (
                    <View className="agent-debug__compact-result">
                      <View className="agent-debug__metric-grid">
                        <Metric label="Active" value={opsAlertResult.activeAlertCount} />
                        <Metric label="Resolved" value={opsAlertResult.resolvedCount} />
                        <Metric label="Notified" value={opsAlertResult.notifiedCount} />
                      </View>
                      <ResultRows title="Alert Actions" rows={opsAlertResult.alerts as unknown as Record<string, unknown>[]} />
                    </View>
                  ) : null}
                  <ResultRows title="Open Alerts" rows={opsAlerts as unknown as Record<string, unknown>[]} />
                  <ResultRows title="Ops Events" rows={opsOverview.events} />
                </>
              ) : (
                <Text className="agent-debug-result__empty">暂无数据</Text>
              )}
            </View>

            <View className="agent-debug__panel">
              <View className="agent-debug__panel-head">
                <View>
                  <Text className="agent-debug__panel-title">P2 Readiness</Text>
                  <Text className="agent-debug__subtitle">{readiness?.generatedAt || "未刷新"}</Text>
                </View>
                <Button
                  className="agent-debug__mini-button"
                  loading={loadingKey === "ops"}
                  disabled={!!loadingKey}
                  onClick={refreshOpsOnly}
                >
                  刷新
                </Button>
              </View>
              {readiness ? (
                <>
                  <View className="agent-debug__health-line">
                    <Text className={`agent-debug__health-badge is-${readiness.status || "unknown"}`}>
                      {asText(readiness.status)}
                    </Text>
                    <Text className="agent-debug__hint" selectable>
                      {asText(readiness.summary)}
                    </Text>
                  </View>
                  <View className="agent-debug__metric-grid">
                    <Metric label="Checks" value={readinessTotals.checks} />
                    <Metric label="Passed" value={readinessTotals.passed} />
                    <Metric label="Warning" value={readinessTotals.warning} />
                    <Metric label="Failed" value={readinessTotals.failed} />
                  </View>
                  <ResultRows title="Dual Entry" rows={readiness.dualEntry} />
                  <ResultRows title="Permission" rows={readiness.permission} />
                  <ResultRows title="Release" rows={readiness.release} />
                </>
              ) : (
                <Text className="agent-debug-result__empty">暂无验收数据</Text>
              )}
            </View>

            <View className="agent-debug__panel">
              <View className="agent-debug__panel-head">
                <View>
                  <Text className="agent-debug__panel-title">Tool Capabilities</Text>
                  <Text className="agent-debug__subtitle">Grant / Role / Schema</Text>
                </View>
                <Button
                  className="agent-debug__mini-button"
                  loading={loadingKey === "ops"}
                  disabled={!!loadingKey}
                  onClick={refreshOpsOnly}
                >
                  刷新
                </Button>
              </View>
              <View className="agent-debug__metric-grid">
                <Metric label="Granted" value={capabilityRows.length} />
                <Metric label="Available" value={availableCapabilityRows.length} />
                <Metric label="Blocked" value={blockedCapabilityRows.length} />
                <Metric label="Runtime" value={runtimeCapabilityRows.length} />
                <Metric label="P3" value={p3CapabilityRows.length} />
                <Metric label="Groups" value={Object.keys(capabilityGroups).length} />
              </View>
              <ResultRows title="P3 Business Tools" rows={p3CapabilityRows as unknown as Row[]} />
              <ResultRows title="Blocked Tools" rows={blockedCapabilityRows as unknown as Row[]} />
            </View>

            <View className="agent-debug__panel">
              <View className="agent-debug__panel-head">
                <Text className="agent-debug__panel-title">Context Preview</Text>
                <View className="agent-debug__switch-line">
                  <Text>Prompt</Text>
                  <Switch
                    checked={includePromptBlock}
                    color="#123e7c"
                    onChange={(e) => setIncludePromptBlock(e.detail.value)}
                  />
                </View>
              </View>
              <View className="agent-debug__field">
                <Text className="agent-debug__field-label">Query</Text>
                <Input
                  className="agent-debug__input"
                  value={query}
                  placeholder="输入检索问题"
                  onInput={(e) => setQuery(e.detail.value)}
                />
              </View>
              <Button
                className="agent-debug__primary-button"
                loading={loadingKey === "preview"}
                disabled={!!loadingKey}
                onClick={runPreview}
              >
                Preview
              </Button>
            </View>

            {preview ? (
              <View className="agent-debug__panel">
                <View className="agent-debug__metric-grid">
                  <Metric label="Recent" value={preview.meta?.recentMessageCount} />
                  <Metric label="Summary" value={preview.meta?.summaryCount} />
                  <Metric label="Action" value={preview.meta?.pendingActionCount} />
                  <Metric label="Memory" value={preview.meta?.memoryCount} />
                  <Metric label="Knowledge" value={preview.meta?.knowledgeCount} />
                  <Metric
                    label="Budget"
                    value={`${preview.meta?.contextBudget?.usedChars || 0}/${preview.meta?.contextBudget?.maxChars || 0}`}
                  />
                  <Metric label="Trim" value={preview.meta?.contextBudget?.truncated ? "yes" : "no"} />
                <Metric label="Remain" value={preview.meta?.contextBudget?.remainingChars} />
                <Metric label="Feedback" value={(preview.feedbackSummary as Record<string, unknown> | undefined)?.total} />
                <Metric label="Down" value={(preview.feedbackSummary as Record<string, unknown> | undefined)?.down} />
                <Metric label="Prompt" value={preview.promptRuntime?.version} />
                <Metric label="PSource" value={preview.promptRuntime?.source} />
              </View>
                <ResultRows
                  title="Context Budget"
                  rows={preview.meta?.contextBudget?.sections as Record<string, unknown>[] | undefined}
                />
                <ResultRows title="Feedback" rows={preview.feedback as Record<string, unknown>[] | undefined} />
                <ResultRows title="Recent Messages" rows={preview.recentMessages} />
                <ResultRows title="Summaries" rows={preview.summaries} />
                <ResultRows title="Pending Actions" rows={preview.pendingActions} />
                <ResultRows title="Memories" rows={preview.memories} />
                <ResultRows title="Knowledge" rows={preview.knowledge} />
                <ResultRows title="Sources" rows={preview.sources as Record<string, unknown>[] | undefined} />
                {preview.promptBlock ? (
                  <View className="agent-debug-result">
                    <View className="agent-debug-result__head">
                      <Text className="agent-debug-result__title">Prompt Block</Text>
                      <Text className="agent-debug-result__count">{preview.promptBlock.length}</Text>
                    </View>
                    <Text className="agent-debug__code" selectable>
                      {preview.promptBlock}
                    </Text>
                  </View>
                ) : null}
              </View>
            ) : null}

            <View className="agent-debug__panel">
              <View className="agent-debug__panel-head">
                <Text className="agent-debug__panel-title">Prompt / Model</Text>
                <Text className="agent-debug__muted">版本与灰度</Text>
              </View>
              <View className="agent-debug__metric-grid">
                <Metric label="Version" value={promptCurrent?.version} />
                <Metric label="Source" value={promptCurrent?.source} />
                <Metric label="Model" value={promptCurrent?.modelCode} />
                <Metric label="Mode" value={promptCurrent?.rolloutMode} />
                <Metric label="Percent" value={promptCurrent?.rolloutPercent} />
                <Metric label="Length" value={promptCurrent?.systemPromptLength} />
              </View>
              <View className="agent-debug__inline-fields">
                <View className="agent-debug__field">
                  <Text className="agent-debug__field-label">版本号</Text>
                  <Input
                    className="agent-debug__input"
                    value={promptDraftVersion}
                    placeholder="manual-版本号"
                    onInput={(e) => setPromptDraftVersion(e.detail.value)}
                  />
                </View>
                <View className="agent-debug__field">
                  <Text className="agent-debug__field-label">标题</Text>
                  <Input
                    className="agent-debug__input"
                    value={promptDraftTitle}
                    placeholder="Prompt标题"
                    onInput={(e) => setPromptDraftTitle(e.detail.value)}
                  />
                </View>
              </View>
              <View className="agent-debug__inline-fields">
                <View className="agent-debug__field">
                  <Text className="agent-debug__field-label">灰度模式</Text>
                  <Input
                    className="agent-debug__input"
                    value={promptRolloutMode}
                    placeholder="full/canary/shadow/off"
                    onInput={(e) => setPromptRolloutMode(e.detail.value)}
                  />
                </View>
                <View className="agent-debug__field agent-debug__field--small">
                  <Text className="agent-debug__field-label">比例</Text>
                  <Input
                    className="agent-debug__input"
                    type="number"
                    value={promptRolloutPercent}
                    placeholder="100"
                    onInput={(e) => setPromptRolloutPercent(e.detail.value)}
                  />
                </View>
              </View>
              <View className="agent-debug__field">
                <Text className="agent-debug__field-label">System Prompt</Text>
                <Textarea
                  className="agent-debug__textarea"
                  value={promptDraftBody}
                  maxlength={30000}
                  placeholder="当前Prompt会自动填入，可在此编辑后保存为草稿"
                  onInput={(e) => setPromptDraftBody(e.detail.value)}
                />
              </View>
              <Button
                className="agent-debug__primary-button"
                loading={loadingKey === "prompt-save"}
                disabled={!!loadingKey}
                onClick={savePromptDraft}
              >
                保存草稿
              </Button>
              <Button
                className="agent-debug__secondary-button"
                loading={loadingKey === "prompt-monitor"}
                disabled={!!loadingKey}
                onClick={monitorPromptRollouts}
              >
                Monitor Rollouts
              </Button>
              {promptMonitorResult ? (
                <View className="agent-debug__compact-result">
                  <View className="agent-debug__metric-grid">
                    <Metric label="Scanned" value={promptMonitorResult.scannedCount} />
                    <Metric label="Failed" value={promptMonitorResult.failedCount} />
                    <Metric label="Actions" value={promptMonitorResult.actionCount} />
                  </View>
                  <ResultRows title="Auto Actions" rows={promptMonitorResult.actions} />
                </View>
              ) : null}
              <View className="agent-debug-result">
                <View className="agent-debug-result__head">
                  <Text className="agent-debug-result__title">Prompt Versions</Text>
                  <Text className="agent-debug-result__count">{promptVersions.length}</Text>
                </View>
                {promptVersions.length ? (
                  promptVersions.map((item) => (
                    <View key={item.id || item.version} className="agent-debug-row">
                      <View className="agent-debug-row__top">
                        <Text className="agent-debug-row__title">
                          {item.version || "-"} · {item.title || "-"}
                        </Text>
                        <Text className="agent-debug-row__tag">{item.status || "-"}</Text>
                      </View>
                      <Text className="agent-debug-row__body" selectable>
                        {`${item.rolloutMode || "-"} ${item.rolloutPercent ?? "-"}% · ${item.modelCode || "default"} · ${item.systemPromptLength || 0} chars`}
                      </Text>
                      <Text className="agent-debug-row__body" selectable>
                        {`gate: ${item.qualityGate?.status || "unknown"} · eval ${item.qualityGate?.latestEvalScore ?? "-"} · down ${item.qualityGate?.latestFeedbackDownRate ?? "-"}% · ${item.qualityGate?.reason || "-"}`}
                      </Text>
                      {item.lastAutoAction ? (
                        <Text className="agent-debug-row__body" selectable>
                          {`auto: ${item.lastAutoAction} · ${item.lastAutoActionAt || "-"} · ${item.lastAutoActionReason || "-"}`}
                        </Text>
                      ) : null}
                      <View className="agent-debug-row__actions">
                        <Button
                          className="agent-debug__mini-button"
                          loading={loadingKey === `prompt-gate-${item.id}`}
                          disabled={!!loadingKey}
                          onClick={() => checkPromptGate(item)}
                        >
                          检查
                        </Button>
                        <Button
                          className="agent-debug__mini-button"
                          loading={loadingKey === `prompt-activate-${item.id}`}
                          disabled={!!loadingKey || item.status === "active"}
                          onClick={() => activatePrompt(item)}
                        >
                          激活
                        </Button>
                        <Button
                          className="agent-debug__mini-button is-muted"
                          loading={loadingKey === `prompt-archive-${item.id}`}
                          disabled={!!loadingKey || item.status === "archived"}
                          onClick={() => archivePrompt(item)}
                        >
                          归档
                        </Button>
                      </View>
                    </View>
                  ))
                ) : (
                  <Text className="agent-debug-result__empty">0</Text>
                )}
              </View>
            </View>

            <View className="agent-debug__panel">
              <View className="agent-debug__panel-head">
                <Text className="agent-debug__panel-title">Eval Harness</Text>
                <Text className="agent-debug__muted">真实 chat 链路回归</Text>
              </View>
              <View className="agent-debug__metric-grid">
                <Metric label="Runs30d" value={evalSummary?.runCount30d} />
                <Metric label="Avg" value={evalSummary?.avgScore30d} />
                <Metric label="Passed" value={evalSummary?.passedCases30d} />
                <Metric label="Failed" value={evalSummary?.failedCases30d} />
              </View>
              <Button
                className="agent-debug__primary-button"
                loading={loadingKey === "eval"}
                disabled={!!loadingKey}
                onClick={runEval}
              >
                Run Eval
              </Button>
              {evalResult ? (
                <View className="agent-debug__compact-result">
                  <View className="agent-debug__metric-grid">
                    <Metric label="Score" value={evalResult.avgScore} />
                    <Metric label="Pass" value={evalResult.passedCount} />
                    <Metric label="Warn" value={evalResult.warningCount} />
                    <Metric label="Fail" value={evalResult.failedCount} />
                  </View>
                  <ResultRows title="Eval Results" rows={evalResult.results as Record<string, unknown>[] | undefined} />
                </View>
              ) : null}
              <ResultRows title="Eval Comparison" rows={evalComparison as unknown as Record<string, unknown>[]} />
              <ResultRows title="Recent Eval Runs" rows={evalRuns as unknown as Record<string, unknown>[]} />
            </View>

            <View className="agent-debug__panel">
              <View className="agent-debug__panel-head">
                <Text className="agent-debug__panel-title">Manual Compact</Text>
                <View className="agent-debug__switch-line">
                  <Text>Memory</Text>
                  <Switch
                    checked={extractMemories}
                    color="#059669"
                    onChange={(e) => setExtractMemories(e.detail.value)}
                  />
                </View>
              </View>
              <Button
                className="agent-debug__danger-button"
                loading={loadingKey === "compact"}
                disabled={!!loadingKey}
                onClick={runCompact}
              >
                Compact
              </Button>
              {compactResult ? (
                <View className="agent-debug__compact-result">
                  <View className="agent-debug__metric-grid">
                    <Metric label="Summary" value={compactResult.summaryCount} />
                    <Metric label="Memory" value={compactResult.memoryCount} />
                    <Metric label="Embedding" value={compactResult.embeddingCount} />
                  </View>
                  <ResultRows title="Created Summaries" rows={compactResult.createdSummaries} />
                  <ResultRows title="Created Memories" rows={compactResult.createdMemories} />
                  <View className="agent-debug-result">
                    <View className="agent-debug-result__head">
                      <Text className="agent-debug-result__title">Raw</Text>
                      <Text className="agent-debug-result__count">JSON</Text>
                    </View>
                    <Text className="agent-debug__code" selectable>
                      {formatJson(compactResult, 2400)}
                    </Text>
                  </View>
                </View>
              ) : null}
            </View>
          </View>
        </ScrollView>
      </View>
    </AdminGuard>
  );
}
