KnowledgePanel.tsx 36.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
import {
  Ban, BookmarkCheck, Clock, Flame, FunctionSquare, Loader2, MessagesSquare, Pencil, Play, Plus, Save, ScrollText,
  Search, Trash2,
} from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { api } from "@/lib/api";
import { errText, onto, type MemFact } from "@/lib/onto";
import { cn, formatTime } from "@/lib/utils";
import { toast } from "@/store/useAppStore";
import { useSqlStore } from "@/store/useSqlStore";
import {
  Badge, Card, CardHeader, Confirm, CopyButton, Empty, ErrorNote, Field, Modal, Segmented, Spinner,
} from "@/components/ui";
import type { SmMetric, SmMetricIssue, SmModel, SqlPair } from "@/lib/types";

type Sec = "pairs" | "hints" | "metrics";

/**
 * 知识库(对标 WrenAI 的 Knowledge):让生成 SQL 越问越准的三样东西。
 * - 问答示例:问题 ↔ SQL,采纳后当作范例参与同类问题的生成;
 * - 取数规则:每次生成都必须遵守的约定(和记忆中心「取数提示」是同一份数据);
 * - 指标:本体里的聚合函数,在这里就地新建 / 编辑 / 试算,保存即发布。
 * 表间关联只在「表与字段」里维护,这里不重复。
 */
export function KnowledgePanel({ dsId, canEdit, onOpenConsole }: {
  dsId: number; canEdit: boolean; onOpenConsole: () => void;
}) {
  const [sec, setSec] = useState<Sec>("pairs");
  return (
    <div className="space-y-3">
      <Segmented<Sec> value={sec} onChange={setSec} options={[
        { key: "pairs", label: <span className="inline-flex items-center gap-1.5"><BookmarkCheck className="h-3.5 w-3.5" />问答示例</span> },
        { key: "hints", label: <span className="inline-flex items-center gap-1.5"><ScrollText className="h-3.5 w-3.5" />取数规则</span> },
        { key: "metrics", label: <span className="inline-flex items-center gap-1.5"><FunctionSquare className="h-3.5 w-3.5" />指标</span> },
      ]} />
      {sec === "pairs" ? <PairsSection dsId={dsId} onOpenConsole={onOpenConsole} />
        : sec === "hints" ? <HintsSection dsId={dsId} canEdit={canEdit} />
        : <MetricsSection dsId={dsId} canEdit={canEdit} />}
    </div>
  );
}

/**
 * 问答示例(原「沉淀库」)。
 *
 * 这里堆的是「跑通过的问答对」,而只有 verified 的那些才会当 few-shot 参与生成 ——
 * 所以页面的首要职责是**让人分得清哪些在生效**,其次才是翻历史。
 * 以前是一条一条平铺、每条都把整段 SQL 摊开,几十条下去全是代码块,
 * 正在生效的那几条反而找不到。现在:先按状态分段、默认收起 SQL、详情点开看。
 */
const STATUS_META: Record<string, { label: string; tone: string; hint: string }> = {
  draft: { label: "草稿", tone: "bg-warn/10 text-warn", hint: "自动捕获,还没人确认过,不参与生成" },
  verified: { label: "已采纳", tone: "bg-ok/10 text-ok", hint: "会作为示例参与同类问题的生成" },
  deprecated: { label: "已停用", tone: "bg-ink/5 text-muted", hint: "不再参与生成" },
};

const SOURCE_TEXT: Record<string, string> = {
  auto: "执行成功自动留存",
  user_saved: "人工保存",
  user_edited: "用户改过 SQL 后跑通",
};

type Filter = "" | "verified" | "draft" | "deprecated";
type Sort = "smart" | "recent" | "hit";

function PairsSection({ dsId, onOpenConsole }: { dsId: number; onOpenConsole?: () => void }) {
  const [creating, setCreating] = useState(false);
  const [draft, setDraft] = useState({ question: "", sql: "", note: "" });
  const [saving, setSaving] = useState(false);
  const [items, setItems] = useState<SqlPair[] | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [status, setStatus] = useState<Filter>("");
  const [sort, setSort] = useState<Sort>("smart");
  const [keyword, setKeyword] = useState("");
  const [detail, setDetail] = useState<SqlPair | null>(null);
  const [confirmDel, setConfirmDel] = useState<SqlPair | null>(null);

  const load = useCallback(() => {
    api.sqlPairs({ dsId, status: status || undefined, keyword })
      .then((d) => { setItems(d); setError(null); })
      .catch((e) => setError(e instanceof Error ? e.message : String(e)));
  }, [dsId, status, keyword]);

  useEffect(() => {
    const t = window.setTimeout(load, keyword ? 250 : 0);
    return () => window.clearTimeout(t);
  }, [load, keyword]);

  const setPairStatus = async (p: SqlPair, next: string) => {
    try {
      if (next === "verified") await api.adoptSqlPair(p.id);
      else await api.updateSqlPair(p.id, { status: next });
      toast("ok", next === "verified" ? "已采纳" : "已停用",
            next === "verified" ? "同类问题之后会参照这条来生成" : undefined);
      setDetail(null);
      load();
    } catch (e) {
      toast("error", "操作失败", e instanceof Error ? e.message : String(e));
    }
  };

  const openDetail = (p: SqlPair) => { setDetail(p); setDraft({ question: p.question, sql: p.sql, note: p.note || "" }); };
  const openNew = () => { setCreating(true); setDraft({ question: "", sql: "", note: "" }); };

  /** 保存前先过一遍只读校验:沉淀库里的 SQL 会被当成示例照抄,写错的不能进去 */
  const save = async () => {
    setSaving(true);
    try {
      const v = await api.validateSql({ ds_id: dsId, sql: draft.sql, scope: "debug" });
      const bad = v.issues.filter((i) => i.level === "error");
      if (bad.length) { toast("error", "SQL 校验没通过", bad.map((i) => i.msg).join(";")); return; }
      if (creating) {
        await api.createSqlPair({ ds_id: dsId, question: draft.question.trim(), sql: draft.sql, note: draft.note, status: "verified" });
        toast("ok", "已加入沉淀库", "已采纳,同类问题会参照它生成");
        setCreating(false);
      } else if (detail) {
        await api.updateSqlPair(detail.id, { question: draft.question.trim(), sql: draft.sql, note: draft.note });
        toast("ok", "已保存");
        setDetail(null);
      }
      load();
    } catch (e) {
      toast("error", "保存失败", e instanceof Error ? e.message : String(e));
    } finally { setSaving(false); }
  };

  const openInConsole = (p: SqlPair) => {
    const st = useSqlStore.getState();
    st.setDsId(dsId);
    st.openDraft({ question: p.question, sql: p.sql });
    setDetail(null);
    onOpenConsole?.();
  };

  const remove = async (p: SqlPair) => {
    try {
      await api.deleteSqlPair(p.id);
      setDetail(null);
      load();
    } catch (e) {
      toast("error", "删除失败", e instanceof Error ? e.message : String(e));
    }
    setConfirmDel(null);
  };

  /** 默认排序刻意不是「按时间倒序」:
   *  生效中的(verified)永远排最前,其次是等人确认的草稿,停用的沉底。
   *  这个库是用来「管哪些在生效」的,不是用来翻流水账的。 */
  const sorted = useMemo(() => {
    const list = [...(items ?? [])];
    const rank = (p: SqlPair) => (p.status === "verified" ? 0 : p.status === "draft" ? 1 : 2);
    const time = (p: SqlPair) => new Date(p.created_at ?? 0).getTime();
    if (sort === "recent") return list.sort((a, b) => time(b) - time(a));
    if (sort === "hit") return list.sort((a, b) => b.hit_count - a.hit_count || time(b) - time(a));
    return list.sort((a, b) =>
      rank(a) - rank(b) || b.hit_count - a.hit_count || time(b) - time(a));
  }, [items, sort]);

  if (error) return <ErrorNote onRetry={load}>{error}</ErrorNote>;

  const all = items ?? [];
  const counts = {
    verified: all.filter((p) => p.status === "verified").length,
    draft: all.filter((p) => p.status === "draft").length,
  };

  return (
    <Card>
      <CardHeader
        title="问答示例"
        desc="问题 ↔ SQL 的范例,采纳的会照着写同类问题"
        right={
          <div className="flex flex-wrap items-center gap-2">
            <Segmented<Sort> value={sort} onChange={setSort} options={[
              { key: "smart", label: "生效优先" },
              { key: "hit", label: "按命中" },
              { key: "recent", label: "按时间" },
            ]} />
            <button className="btn btn-primary btn-sm" onClick={openNew}><Plus className="h-3.5 w-3.5" /> 新增示例</button>
          </div>
        } />

      <div className="flex flex-wrap items-center gap-2 border-b border-line px-4 pb-3">
        <div className="relative min-w-[200px] flex-1">
          <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted" />
          <input className="input pl-8" placeholder="搜问题"
                 value={keyword} onChange={(e) => setKeyword(e.target.value)} />
        </div>
        <Segmented<Filter> value={status} onChange={setStatus} options={[
          { key: "", label: "全部" },
          { key: "verified", label: "生效中" },
          { key: "draft", label: "待确认" },
          { key: "deprecated", label: "已停用" },
        ]} />
      </div>

      {!status && (counts.verified > 0 || counts.draft > 0) && (
        <p className="border-b border-line bg-elevated/60 px-4 py-1.5 text-label text-muted">
          <span className="text-ok">{counts.verified} 条正在参与生成</span>
          {counts.draft > 0 && <> · {counts.draft} 条草稿等你确认,确认之后才会生效</>}
        </p>
      )}

      {!items ? (
        <div className="p-4"><Spinner /></div>
      ) : sorted.length === 0 ? (
        <Empty icon={<BookmarkCheck className="h-6 w-6" />}
               title={keyword || status ? "没有匹配的沉淀" : "还没有沉淀"}
               desc={keyword || status ? undefined : "在调试台的回答上点「存为示例」,或手工新增"} />
      ) : (
        <div className="divide-y divide-line">
          {sorted.map((p) => (
            <div key={p.id}
                 className={cn("flex items-center gap-2 px-4 py-2.5 transition-colors hover:bg-ink/[0.02]",
                   p.status === "deprecated" && "opacity-55")}>
              <button className="min-w-0 flex-1 text-left" onClick={() => openDetail(p)}>
                <span className="flex flex-wrap items-center gap-1.5">
                  <span className="min-w-0 truncate text-body font-medium">{p.question}</span>
                  <Badge tone={STATUS_META[p.status]?.tone}>
                    {STATUS_META[p.status]?.label ?? p.status}
                  </Badge>
                  {p.hit_count > 0 && (
                    <Badge tone="bg-brand/10 text-brand" >
                      <Flame className="h-3 w-3" />{p.hit_count}
                    </Badge>
                  )}
                  {p.sql_before && <Badge tone="bg-warn/10 text-warn">人工修正过</Badge>}
                </span>
                {/* SQL 只给一行预览。要看全文点开详情 —— 几十条代码块摊在列表里
                    只会把真正要管的状态信息淹掉 */}
                <span className="mt-0.5 block truncate font-mono text-caption text-muted">
                  {p.sql.replace(/\s+/g, " ").trim()}
                </span>
              </button>
              <div className="flex shrink-0 items-center gap-1">
                {p.status !== "verified" ? (
                  <button className="btn btn-sm" onClick={() => setPairStatus(p, "verified")}>
                    <BookmarkCheck className="h-3.5 w-3.5" /> 采纳
                  </button>
                ) : (
                  <button className="btn btn-ghost btn-sm" onClick={() => setPairStatus(p, "deprecated")}
                          title="停用后不再参与生成">
                    <Ban className="h-3.5 w-3.5" />
                  </button>
                )}
                <button className="btn btn-ghost btn-sm text-bad" onClick={() => setConfirmDel(p)}>
                  <Trash2 className="h-3.5 w-3.5" />
                </button>
              </div>
            </div>
          ))}
        </div>
      )}

      <Modal
        open={!!detail} onClose={() => setDetail(null)} width="max-w-3xl"
        title={detail?.question ?? ""}
        desc={detail ? STATUS_META[detail.status]?.hint : undefined}
        footer={detail && (
          <>
            <span className="mr-auto text-label text-muted">
              {SOURCE_TEXT[detail.source] ?? detail.source} · {formatTime(detail.created_at)}
            </span>
            <button className="btn btn-sm" onClick={() => openInConsole(detail)} title="带着这条 SQL 去调试台改、重跑">
              <MessagesSquare className="h-3.5 w-3.5" /> 在调试台打开
            </button>
            <button className="btn btn-sm" disabled={saving || !draft.question.trim() || !draft.sql.trim()
                      || (draft.question === detail.question && draft.sql === detail.sql && draft.note === (detail.note || ""))}
                    onClick={() => void save()}>
              {saving ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Save className="h-3.5 w-3.5" />} 保存修改
            </button>
            {detail.status !== "verified" ? (
              <button className="btn btn-primary btn-sm" onClick={() => setPairStatus(detail, "verified")}>
                <BookmarkCheck className="h-3.5 w-3.5" /> 采纳为示例
              </button>
            ) : (
              <button className="btn btn-sm" onClick={() => setPairStatus(detail, "deprecated")}>
                <Ban className="h-3.5 w-3.5" /> 停用
              </button>
            )}
          </>
        )}>
        {detail && (
          <div className="space-y-3">
            <div className="flex flex-wrap items-center gap-1.5">
              <Badge tone={STATUS_META[detail.status]?.tone}>
                {STATUS_META[detail.status]?.label ?? detail.status}
              </Badge>
              <Badge tone="bg-ink/5 text-muted">
                <Clock className="h-3 w-3" />{formatTime(detail.created_at)}
              </Badge>
              {detail.hit_count > 0 && (
                <Badge tone="bg-brand/10 text-brand">被复用 {detail.hit_count} 次</Badge>
              )}
              {detail.models_used.map((t) => (
                <Badge key={t} tone="bg-ink/5 text-muted">{t}</Badge>
              ))}
            </div>

            <PairFields draft={draft} setDraft={setDraft} />

            {detail.sql_before && (
              <div>
                <p className="mb-1 text-label font-medium text-muted">
                  模型原本生成的版本(被人工改掉了)
                </p>
                <pre className="overflow-x-auto rounded-md bg-bad/[0.06] p-2.5 font-mono
                                text-label leading-relaxed">{detail.sql_before}</pre>
                <p className="mt-1 text-label text-muted">
                  这种「改过才跑通」的记录最值钱:它直接标出了模型的系统性偏差。
                  采纳之后,同类问题会照着改后的版本生成。
                </p>
              </div>
            )}
          </div>
        )}
      </Modal>

      <Modal open={creating} onClose={() => setCreating(false)} width="max-w-3xl" title="新增示例"
             desc="写一个业务问题和它对应的正确 SQL。保存前会做只读校验,保存后直接采纳生效。"
             footer={<>
               <button className="btn btn-sm" onClick={() => setCreating(false)}>取消</button>
               <button className="btn btn-primary btn-sm" disabled={saving || !draft.question.trim() || !draft.sql.trim()}
                       onClick={() => void save()}>
                 {saving && <Loader2 className="h-3.5 w-3.5 animate-spin" />}保存并采纳</button>
             </>}>
        <PairFields draft={draft} setDraft={setDraft} />
      </Modal>

      <Confirm
        open={!!confirmDel} danger title="删除这条沉淀?"
        body={confirmDel?.question ?? ""} confirmText="删除"
        onConfirm={() => confirmDel && remove(confirmDel)}
        onClose={() => setConfirmDel(null)} />
    </Card>
  );
}

type PairDraft = { question: string; sql: string; note: string };

function PairFields({ draft, setDraft }: { draft: PairDraft; setDraft: (d: PairDraft) => void }) {
  return (
    <div className="space-y-3">
      <Field label="业务问题" required hint="用业务同事会说的话写,召回时按它匹配">
        <input className="input" value={draft.question} placeholder="如:本月各门店的配件销售额"
               onChange={(e) => setDraft({ ...draft, question: e.target.value })} />
      </Field>
      <Field label={<span className="flex items-center gap-1.5">SQL<span className="flex-1" />
                     {draft.sql && <CopyButton text={draft.sql} />}</span>} required>
        <textarea className="input min-h-[180px] font-mono text-label leading-relaxed" value={draft.sql}
                  spellCheck={false} placeholder="SELECT ..."
                  onChange={(e) => setDraft({ ...draft, sql: e.target.value })} />
      </Field>
      <Field label="备注" hint="口径说明、为什么这么写,给后来维护的人看">
        <input className="input" value={draft.note} onChange={(e) => setDraft({ ...draft, note: e.target.value })} />
      </Field>
    </div>
  );
}

/* ================================ 取数规则 ================================ */

/** 常见的取数约定,点一下填进输入框再改。都是「写 SQL 时不说就会错」的那类事 */
const TEMPLATES = [
  "统计订单类数据时,默认排除状态为「已取消」「已作废」的记录",
  "金额字段单位是元;超过一万的金额换算成「万元」,保留两位小数",
  "「本月」「上月」按自然月算,以单据日期为准",
  "门店名称以门店表为准,不要用单据里冗余的门店名字段",
];

function HintsSection({ dsId, canEdit }: { dsId: number; canEdit: boolean }) {
  const [hints, setHints] = useState<MemFact[] | null>(null);
  const [editing, setEditing] = useState<MemFact | "new" | null>(null);
  const [del, setDel] = useState<MemFact | null>(null);

  const load = useCallback(() => {
    onto.memFacts({ kind: "sql_hint" })
      // 只看对所有数据源生效的、和对当前数据源生效的
      .then((h) => setHints(h.filter((f) => !f.scope_ref || f.scope_ref === String(dsId))))
      .catch((e) => { setHints([]); toast("error", "加载失败", errText(e)); });
  }, [dsId]);
  useEffect(load, [load]);

  const toggle = async (f: MemFact) => {
    try { await onto.saveMemFact(f.id, { status: f.status === "active" ? "deprecated" : "active" }); load(); }
    catch (e) { toast("error", "操作失败", errText(e)); }
  };
  const remove = async (f: MemFact) => {
    try { await onto.deleteMemFact(f.id); load(); } catch (e) { toast("error", "删除失败", errText(e)); }
    setDel(null);
  };

  if (!hints) return <Card className="p-4"><Spinner /></Card>;
  return (
    <Card>
      <CardHeader title="取数规则"
                  desc="生成每一条 SQL 都必须遵守的约定,调试台和提问页都生效"
                  right={canEdit && <button className="btn btn-primary btn-sm" onClick={() => setEditing("new")}>
                    <Plus className="h-3.5 w-3.5" /> 新增规则</button>} />
      {hints.length === 0 ? (
        <Empty icon={<ScrollText className="h-6 w-6" />} title="还没有规则"
               desc="经常取错的地方写一句规则,或在调试台的回答上点「加规则」" />
      ) : (
        <div className="divide-y divide-line">
          {hints.map((h) => (
            <div key={h.id} className={cn("flex items-center gap-3 px-5 py-2.5", h.status !== "active" && "opacity-55")}>
              <p className="min-w-0 flex-1 text-body leading-relaxed">{h.text}</p>
              <Badge tone={h.scope_ref ? "bg-brand/10 text-brand" : "bg-ink/5 text-muted"} className="shrink-0">
                {h.scope_ref ? "本数据源" : "全部数据源"}
              </Badge>
              <span className="w-16 shrink-0 text-right text-caption tabular-nums text-muted" title="带进生成的次数">用过 {h.hits}</span>
              {canEdit && (
                <span className="flex shrink-0 items-center gap-1">
                  <label className="flex items-center gap-1 text-label text-muted">
                    <input type="checkbox" checked={h.status === "active"} onChange={() => void toggle(h)} />启用
                  </label>
                  <button className="btn btn-ghost btn-sm" onClick={() => setEditing(h)} title="编辑"><Pencil className="h-3.5 w-3.5" /></button>
                  <button className="btn btn-ghost btn-sm text-bad" onClick={() => setDel(h)} title="删除"><Trash2 className="h-3.5 w-3.5" /></button>
                </span>
              )}
            </div>
          ))}
        </div>
      )}
      {editing && <HintForm dsId={dsId} fact={editing === "new" ? null : editing}
                            onClose={() => setEditing(null)} onSaved={() => { setEditing(null); load(); }} />}
      <Confirm open={!!del} danger title="删除这条规则?" body={del?.text ?? ""} confirmText="删除"
               onConfirm={() => del && remove(del)} onClose={() => setDel(null)} />
    </Card>
  );
}

/** 新增 / 编辑一条取数规则。SQL 调试台的「加规则」也用它 */
export function HintForm({ dsId, fact, onClose, onSaved }: {
  dsId: number; fact: MemFact | null; onClose: () => void; onSaved: () => void;
}) {
  const [text, setText] = useState(fact?.text ?? "");
  const [onlyThis, setOnlyThis] = useState(fact ? !!fact.scope_ref : true);
  const [busy, setBusy] = useState(false);
  const save = async () => {
    setBusy(true);
    const scope_ref = onlyThis ? String(dsId) : "";
    try {
      if (fact) await onto.saveMemFact(fact.id, { text: text.trim(), kind: "sql_hint", scope_ref });
      else await onto.addMemFact({ text: text.trim(), kind: "sql_hint", scope: "workspace", scope_ref });
      toast("ok", fact ? "已保存" : "已加入知识库", "下一次生成 SQL 开始遵守");
      onSaved();
    } catch (e) { toast("error", "保存失败", errText(e)); } finally { setBusy(false); }
  };
  return (
    <Modal open onClose={onClose} title={fact ? "编辑规则" : "新增规则"} width="max-w-xl"
           footer={<>
             <button className="btn btn-sm" onClick={onClose}>取消</button>
             <button className="btn btn-primary btn-sm" disabled={busy || !text.trim()} onClick={() => void save()}>
               {busy && <Loader2 className="h-3.5 w-3.5 animate-spin" />}保存</button>
           </>}>
      <div className="space-y-3">
        <textarea className="input min-h-[96px] leading-relaxed" value={text} autoFocus
                  placeholder="像交代新同事一样写:什么情况下、要怎么取"
                  onChange={(e) => setText(e.target.value)} />
        {!fact && (
          <div className="flex flex-wrap gap-1.5">
            {TEMPLATES.map((t) => <button key={t} className="chip text-label" onClick={() => setText(t)}>{t}</button>)}
          </div>
        )}
        <div className="flex flex-wrap gap-4 text-body">
          <label className="flex items-center gap-1.5">
            <input type="radio" checked={onlyThis} onChange={() => setOnlyThis(true)} />只对当前数据源
          </label>
          <label className="flex items-center gap-1.5">
            <input type="radio" checked={!onlyThis} onChange={() => setOnlyThis(false)} />所有数据源
          </label>
        </div>
      </div>
    </Modal>
  );
}

/* ================================ 指标 ================================ */

const AGGS = [
  { key: "SUM", label: "求和" }, { key: "COUNT", label: "计数" }, { key: "COUNT_DISTINCT", label: "去重计数" },
  { key: "AVG", label: "平均" }, { key: "MAX", label: "最大" }, { key: "MIN", label: "最小" },
];
const exprOf = (agg: string, col: string) =>
  agg === "COUNT" && !col ? "COUNT(*)" : agg === "COUNT_DISTINCT" ? `COUNT(DISTINCT ${col})` : `${agg}(${col})`;
/** 把已有表达式拆回「聚合方式 + 字段」;拆不开就当自定义表达式 */
function parseExpr(expr: string): { agg: string; col: string } | null {
  const m = expr.trim().match(/^(SUM|COUNT|AVG|MAX|MIN)\(\s*(DISTINCT\s+)?([A-Za-z_][\w.]*|\*)\s*\)$/i);
  if (!m) return null;
  const agg = m[2] ? "COUNT_DISTINCT" : m[1].toUpperCase();
  return { agg, col: m[3] === "*" ? "" : m[3] };
}

function MetricsSection({ dsId, canEdit }: { dsId: number; canEdit: boolean }) {
  const [metrics, setMetrics] = useState<SmMetric[] | null>(null);
  const [issues, setIssues] = useState<SmMetricIssue[]>([]);
  const [models, setModels] = useState<SmModel[]>([]);
  const [editing, setEditing] = useState<SmMetric | "new" | null>(null);
  const [trial, setTrial] = useState<SmMetric | null>(null);

  const load = useCallback(() => {
    Promise.all([api.sqlMetrics(dsId), api.metricIssues(dsId), api.sqlModels(dsId)])
      .then(([m, i, md]) => { setMetrics(m); setIssues(i); setModels(md); })
      .catch((e) => { setMetrics([]); toast("error", "加载失败", errText(e)); });
  }, [dsId]);
  useEffect(load, [load]);

  const tableOf = useMemo(() => new Map(models.map((m) => [m.id, m.physical_table])), [models]);
  if (!metrics) return <Card className="p-4"><Spinner /></Card>;

  return (
    <Card>
      <CardHeader title="指标"
                  desc="问到这些指标时直接按这里的公式和口径算,不让 AI 自己拼"
                  right={canEdit && <button className="btn btn-primary btn-sm" onClick={() => setEditing("new")}>
                    <Plus className="h-3.5 w-3.5" /> 新增指标</button>} />
      {metrics.length === 0 ? (
        <Empty icon={<FunctionSquare className="h-6 w-6" />} title="还没有指标"
               desc="把常问的数(库存总量、缺货率……)定义成指标,口径就固定下来了" />
      ) : (
        <div className="divide-y divide-line">
          {metrics.map((m) => {
            const its = issues.filter((i) => i.metric_id === m.id);
            return (
              <div key={m.id} className="flex items-center gap-3 px-5 py-2.5">
                <div className="min-w-0 flex-1">
                  <p className="flex flex-wrap items-center gap-2">
                    <span className="text-body font-medium">{m.display_name || m.name}</span>
                    <code className="text-label text-muted">{m.expression}</code>
                    {tableOf.get(m.base_model_id) && <Badge tone="bg-ink/5 text-muted">{tableOf.get(m.base_model_id)}</Badge>}
                    {its.length > 0 && <Badge tone="bg-bad/10 text-bad" title={its.map((i) => i.reason).join(";")}>有问题,暂不参与问数</Badge>}
                  </p>
                  {m.calibre_note && <p className="mt-0.5 truncate text-label text-muted" title={m.calibre_note}>口径:{m.calibre_note}</p>}
                </div>
                <button className="btn btn-sm shrink-0" onClick={() => setTrial(m)}><Play className="h-3.5 w-3.5" />试算</button>
                {canEdit && <button className="btn btn-ghost btn-sm shrink-0" onClick={() => setEditing(m)} title="编辑">
                  <Pencil className="h-3.5 w-3.5" /></button>}
              </div>
            );
          })}
        </div>
      )}
      {editing && <MetricForm dsId={dsId} models={models} metric={editing === "new" ? null : editing}
                              onClose={() => setEditing(null)} onSaved={() => { setEditing(null); load(); }} />}
      {trial && <MetricTrial metric={trial} onClose={() => setTrial(null)} />}
    </Card>
  );
}

type MetricDraft = {
  name: string; table: string; agg: string; col: string; custom: string; useCustom: boolean;
  time: string; dims: string[]; filters: string; unit: string; calibre: string;
};

function MetricForm({ dsId, models, metric, onClose, onSaved }: {
  dsId: number; models: SmModel[]; metric: SmMetric | null; onClose: () => void; onSaved: () => void;
}) {
  const [d, setD] = useState<MetricDraft>({
    name: "", table: models[0]?.physical_table ?? "", agg: "SUM", col: "", custom: "", useCustom: false,
    time: "", dims: [], filters: "", unit: "", calibre: "",
  });
  const [busy, setBusy] = useState(false);
  const [loaded, setLoaded] = useState(!metric);

  // 编辑:从本体里读回这个函数的口径和取数绑定
  useEffect(() => {
    if (!metric) return;
    void onto.concept(metric.id).then((c) => {
      const b = c.bindings.find((x) => x.target_kind === "metric_expr" && x.ds_id === dsId);
      const ref = (b?.ref || {}) as any;
      const parsed = parseExpr(ref.expression || "");
      setD({
        name: c.display_name || c.name, table: ref.base_table || "",
        agg: parsed?.agg ?? "SUM", col: parsed?.col ?? "", custom: ref.expression || "", useCustom: !parsed,
        time: ref.time_column || "", dims: Object.values(ref.dimensions || {}) as string[],
        filters: (ref.filters || []).join("\n"), unit: c.spec?.unit || "", calibre: c.spec?.formula_text || c.description || "",
      });
      setLoaded(true);
    }).catch((e) => toast("error", "加载失败", errText(e)));
  }, [metric, dsId]);

  const cols = models.find((m) => m.physical_table === d.table)?.columns ?? [];
  const expression = d.useCustom ? d.custom.trim() : exprOf(d.agg, d.col);
  const exprOk = !!expression && (d.useCustom || d.agg === "COUNT" || !!d.col);
  const ok = d.name.trim() && d.table && exprOk;
  const set = <K extends keyof MetricDraft>(k: K, v: MetricDraft[K]) => setD((x) => ({ ...x, [k]: v }));

  const save = async () => {
    setBusy(true);
    try {
      const body = { name: d.name.trim(), display_name: d.name.trim(), description: d.calibre.trim(),
                     spec: { category: "aggregate", unit: d.unit.trim(), formula_text: d.calibre.trim() } };
      const c = metric ? await onto.updateConcept(metric.id, body) : await onto.createConcept({ kind: "function", ...body });
      await onto.setBinding(c.id, { ds_id: dsId, target_kind: "metric_expr", ref: {
        base_table: d.table, expression, time_column: d.time,
        filters: d.filters.split("\n").map((x) => x.trim()).filter(Boolean),
        dimensions: Object.fromEntries(d.dims.map((x) => [x, x])),
      } });
      // 只发布这一个指标:保存就生效,不用再去发布页
      const r = await onto.proposeRelease(`指标:${body.name}`, true, [c.id]);
      if (r.published) toast("ok", "指标已生效", body.name);
      else toast("warn", "已保存,等待审核后生效", r.cannot_reason || "");
      onSaved();
    } catch (e) { toast("error", "保存失败", errText(e)); } finally { setBusy(false); }
  };


  return (
    <Modal open onClose={onClose} title={metric ? "编辑指标" : "新增指标"} width="max-w-2xl"
           footer={<>
             <button className="btn btn-sm" onClick={onClose}>取消</button>
             <button className="btn btn-primary btn-sm" disabled={!ok || busy || !loaded} onClick={() => void save()}>
               {busy && <Loader2 className="h-3.5 w-3.5 animate-spin" />}保存并生效</button>
           </>}>
      {!loaded ? <Spinner /> : (
        <div className="space-y-3">
          <div className="grid gap-3 sm:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
            <Field label="指标名" required>
              <input className="input" value={d.name} placeholder="如:库存总量" onChange={(e) => set("name", e.target.value)} />
            </Field>
            <Field label="单位">
              <input className="input" value={d.unit} placeholder="件 / 元" onChange={(e) => set("unit", e.target.value)} />
            </Field>
          </div>
          <Field label="统计哪张表" required>
            <select className="input" value={d.table}
                    onChange={(e) => setD((x) => ({ ...x, table: e.target.value, col: "", time: "", dims: [] }))}>
              {models.map((m) => <option key={m.id} value={m.physical_table}>{m.physical_table}{m.description ? `(${m.description})` : ""}</option>)}
            </select>
          </Field>
          <Field label="怎么算" required>
            <label className="mb-1.5 flex items-center gap-1 text-label text-muted">
              <input type="checkbox" checked={d.useCustom} onChange={(e) => set("useCustom", e.target.checked)} />写自定义表达式
            </label>
            {d.useCustom ? (
              <input className="input font-mono" value={d.custom} placeholder="SUM(on_hand) / NULLIF(SUM(safety_stock), 0)"
                     onChange={(e) => set("custom", e.target.value)} />
            ) : (
              <div className="grid grid-cols-[8rem_minmax(0,1fr)] gap-2">
                <select className="input" value={d.agg} onChange={(e) => set("agg", e.target.value)}>
                  {AGGS.map((a) => <option key={a.key} value={a.key}>{a.label}</option>)}
                </select>
                <select className="input" value={d.col} onChange={(e) => set("col", e.target.value)}>
                  <option value="">{d.agg === "COUNT" ? "(行数)" : "选字段…"}</option>
                  {cols.map((c) => <option key={c.id} value={c.name}>{c.name}{c.description ? `(${c.description})` : ""}</option>)}
                </select>
              </div>
            )}
            {exprOk && <code className="mt-1 block text-caption text-muted">{expression}</code>}
          </Field>
          <div className="grid gap-3 sm:grid-cols-2">
            <Field label="时间字段">
              <select className="input" value={d.time} onChange={(e) => set("time", e.target.value)}>
                <option value="">不按时间</option>
                {cols.map((c) => <option key={c.id} value={c.name}>{c.name}</option>)}
              </select>
            </Field>
            <Field label="过滤条件">
              <textarea className="input min-h-[38px] font-mono text-label" rows={1} value={d.filters}
                        placeholder="status <> 'cancelled'(一行一条)" onChange={(e) => set("filters", e.target.value)} />
            </Field>
          </div>
          <Field label="可以按哪些字段拆分">
            <div className="flex max-h-28 flex-wrap gap-1.5 overflow-auto">
              {cols.map((c) => (
                <label key={c.id} className={cn("chip cursor-pointer text-label", d.dims.includes(c.name) && "border-brand/50 bg-brand/10 text-brand")}>
                  <input type="checkbox" className="hidden" checked={d.dims.includes(c.name)}
                         onChange={(e) => set("dims", e.target.checked ? [...d.dims, c.name] : d.dims.filter((x) => x !== c.name))} />
                  {c.name}
                </label>
              ))}
            </div>
          </Field>
          <Field label="口径说明">
            <input className="input" value={d.calibre} placeholder="如:只算在库可用数量,不含在途"
                   onChange={(e) => set("calibre", e.target.value)} />
          </Field>
        </div>
      )}
    </Modal>
  );
}

/** 试算:按当前发布的口径真跑一次,可选一个维度拆开看 */
function MetricTrial({ metric, onClose }: { metric: SmMetric; onClose: () => void }) {
  const [dim, setDim] = useState("");
  const [res, setRes] = useState<any | null>(null);
  const [busy, setBusy] = useState(false);
  const dims = (metric as any).allowed_dimensions as string[] | undefined;
  const run = useCallback(async () => {
    setBusy(true);
    try { setRes(await onto.metricQuery({ metric: metric.id, dimensions: dim ? [dim] : [], limit: 50 })); }
    catch (e) { setRes({ error: errText(e) }); } finally { setBusy(false); }
  }, [metric.id, dim]);
  useEffect(() => { void run(); }, [run]);
  return (
    <Modal open onClose={onClose} title={`试算:${metric.display_name || metric.name}`} width="max-w-2xl">
      <div className="space-y-3">
        {!!dims?.length && (
          <div className="flex flex-wrap items-center gap-1.5 text-label">
            <span className="text-muted">按</span>
            <button className={cn("chip", !dim && "border-brand/50 bg-brand/10 text-brand")} onClick={() => setDim("")}>不拆分</button>
            {dims.map((x) => <button key={x} className={cn("chip", dim === x && "border-brand/50 bg-brand/10 text-brand")} onClick={() => setDim(x)}>{x}</button>)}
          </div>
        )}
        {busy ? <Spinner /> : res?.error ? <p className="text-label text-bad">{res.error}</p> : res && (
          <>
            <div className="max-h-[320px] overflow-auto rounded-lg border border-line">
              <table className="w-full text-label">
                <thead className="sticky top-0 bg-elevated"><tr>{(res.columns || []).map((c: string) => <th key={c} className="px-2.5 py-1.5 text-left font-medium">{c}</th>)}</tr></thead>
                <tbody>{(res.rows || []).map((r: unknown[], i: number) => (
                  <tr key={i} className="border-t border-line">{r.map((v, j) => <td key={j} className="px-2.5 py-1.5 tabular-nums">{v === null ? "—" : String(v)}</td>)}</tr>
                ))}</tbody>
              </table>
            </div>
            {res.sql && <pre className="max-h-32 overflow-auto rounded-md bg-ink/[0.05] p-2 font-mono text-caption">{res.sql}</pre>}
          </>
        )}
      </div>
    </Modal>
  );
}