import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { Inspector } from "@/components/inspector/Inspector";
import { retrievalActivityItem, retrievalAgentItem } from "@/lib/layout";
import type { RetrievalActivity, RetrievalAgentRun } from "@/lib/types";

const queryActivity: RetrievalActivity = {
  id: "event:4607",
  kind: "query",
  label: "毛驴效应 心理学科普",
  status: "hit",
  resultCount: 2,
  detailRef: "event:4607",
};

function agentRun(): RetrievalAgentRun {
  return {
    id: "retrieval-agent:4601",
    kind: "retrieval-agent",
    eventId: 4601,
    agentType: "retrieve_data_decode_case",
    businessLabel: "解构 Case Agent",
    taskPreview: "查找毛驴效应案例",
    status: "completed",
    querySummary: { total: 1, hit: 1, empty: 0, failure: 0, unknown: 0 },
    attempts: [],
    screening: { state: "available", preview: "初筛完成" },
    detailRef: "retrieval-agent:4601",
  };
}

describe("retrieval Inspector", () => {
  it("lists agent queries and delegates same-drawer navigation", () => {
    const onNavigate = vi.fn();
    render(<Inspector
      item={retrievalAgentItem(agentRun(), 1, 2)}
      tab="business"
      onTab={vi.fn()}
      onClose={vi.fn()}
      onNavigate={onNavigate}
      detail={{
        detailKind: "retrieval-agent",
        retrievalKind: "agent",
        businessSections: [
          { id: "task", title: "取数目标", content: "查找毛驴效应案例" },
          { id: "screening", title: "初筛整理", content: "保留两条相关案例" },
        ],
        activities: [queryActivity],
        technical: {},
      }}
    />);

    expect(screen.getByText("查询记录")).toBeInTheDocument();
    expect(screen.getByText("2 条")).toBeInTheDocument();
    fireEvent.click(screen.getByRole("button", { name: /毛驴效应 心理学科普/ }));
    expect(onNavigate).toHaveBeenCalledWith(queryActivity);
  });

  it("shows an explicit notice when Pattern Relation Agent has no structured records", () => {
    render(<Inspector
      item={retrievalAgentItem({ ...agentRun(), agentType: "retrieve_data_pattern_relation", businessLabel: "Pattern / Relation Agent" }, 1, 2)}
      tab="business"
      onTab={vi.fn()}
      onClose={vi.fn()}
      detail={{
        detailKind: "retrieval-agent",
        retrievalKind: "agent",
        activities: [],
        missingActivityNotice: "本次运行未保存可下钻的结构化查询记录。",
        technical: {},
      }}
    />);

    expect(screen.getByText("本次运行未保存可下钻的结构化查询记录。")).toBeInTheDocument();
  });

  it("renders hit cases with expandable complete content", () => {
    render(<Inspector
      item={retrievalActivityItem(queryActivity, 1, 2)}
      tab="business"
      onTab={vi.fn()}
      onClose={vi.fn()}
      onBack={vi.fn()}
      backLabel="返回解构 Case Agent"
      detail={{
        detailKind: "retrieval-event",
        sourceKind: "agent-query",
        eventId: 4607,
        queryConditions: [{ key: "keyword", label: "关键词", value: "毛驴效应" }],
        outcome: { state: "hit", count: 2, message: "查询成功，返回 2 条结果。" },
        items: [{
          id: "case-a",
          title: "每天心理学 · Case 1",
          subtitle: "case-a",
          meta: [{ label: "匹配分数", value: 0.7032 }],
          sections: [{ title: "完整解构内容", value: [{ id: "段落1", description: "完整解构原文" }] }],
        }],
        completeness: { bodyAvailable: true, truncated: false },
        technical: {},
      }}
    />);

    expect(screen.getByText("查询成功，返回 2 条结果。")).toBeInTheDocument();
    expect(screen.getByText("毛驴效应")).toBeInTheDocument();
    expect(screen.getByText("每天心理学 · Case 1")).toBeInTheDocument();
    expect(screen.getByText(/\"完整解构原文\"/)).toBeInTheDocument();
    expect(screen.getByRole("button", { name: "返回解构 Case Agent" })).toBeInTheDocument();
  });

  it("distinguishes successful empty from technical failure", () => {
    const item = retrievalActivityItem({ ...queryActivity, id: "event:4603", detailRef: "event:4603", status: "empty", resultCount: 0 }, 1, 2);
    const { rerender } = render(<Inspector item={item} tab="business" onTab={vi.fn()} onClose={vi.fn()} detail={{
      detailKind: "retrieval-event",
      sourceKind: "agent-query",
      outcome: { state: "empty", count: 0, message: "查询执行成功，没有匹配数据。" },
      queryConditions: [{ key: "account_name", label: "账号", value: "每天一点心理学" }],
      items: [],
      completeness: { bodyAvailable: true, truncated: false },
      technical: {},
    }} />);
    expect(screen.getByText("查询执行成功，没有匹配数据。")).toBeInTheDocument();

    rerender(<Inspector item={{ ...item, id: "event:4066" }} tab="business" onTab={vi.fn()} onClose={vi.fn()} detail={{
      detailKind: "retrieval-event",
      sourceKind: "agent-query",
      outcome: { state: "failure", message: "查询执行失败：return_field 仅支持主脉络。", errorKind: "parameter" },
      queryConditions: [{ key: "return_field", label: "返回内容", value: "写法" }],
      items: [],
      completeness: { bodyAvailable: true, truncated: false },
      technical: {},
    }} />);
    expect(screen.getByText("查询执行失败：return_field 仅支持主脉络。")).toBeInTheDocument();
    expect(screen.getByText("写法")).toBeInTheDocument();
  });
});
