// #region AssistantClarificationIntegrationTest:Module [TYPE Function]
// @SEMANTICS: assistant, clarification, integration-test, dataset-review, mixed-initiative
// @PURPOSE: Verify AssistantChatPanel hosts the resumable dataset-review clarification flow inside the assistant drawer and refreshes workspace session state after answering.
// @LAYER UI (Tests)
// @RELATION DEPENDS_ON -> [EXT:frontend:AssistantChatPanel]

import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent, waitFor } from "@testing-library/svelte";
import AssistantChatPanel from "../AssistantChatPanel.svelte";
import * as assistantApi from "$lib/api/assistant.js";
import { api, requestApi } from "$lib/api.js";
import { setSession as setDatasetReviewSession } from "$lib/stores/datasetReviewSession.svelte.js";

vi.mock("$lib/api/assistant.js", () => ({
  getAssistantHistory: vi.fn(() => Promise.resolve({ items: [], total: 0, has_next: false })),
  getAssistantConversations: vi.fn(() => Promise.resolve({ items: [], total: 0, has_next: false, active_total: 0, archived_total: 0 })),
  deleteAssistantConversation: vi.fn(),
  confirmAssistantOperation: vi.fn(),
  cancelAssistantOperation: vi.fn(),
  sendAssistantMessage: vi.fn(),
}));

vi.mock("$lib/api.js", () => ({
  api: {
    getLlmStatus: vi.fn(() => Promise.resolve({ configured: true, reason: "ok" })),
    fetchApi: vi.fn(),
  },
  requestApi: vi.fn(),
}));

vi.mock("$lib/stores/datasetReviewSession.svelte.js", () => ({
  setSession: vi.fn(),
}));

vi.mock("$lib/toasts.svelte.js", () => ({
  addToast: vi.fn(),
}));

vi.mock("$lib/stores/taskDrawer.svelte.js", () => ({
  openDrawerForTask: vi.fn(),
}));

const { assistantState } = vi.hoisted(() => ({
  assistantState: (() => {
    let value = {
      isOpen: true,
      conversationId: "conv-1",
      datasetReviewSessionId: "session-1",
      seedMessage: "",
      focusTarget: null,
    };
    const subscribers = new Set();
    return {
      subscribe(fn) {
        subscribers.add(fn);
        fn(value);
        return () => subscribers.delete(fn);
      },
      update(updater) {
        value = updater(value);
        subscribers.forEach((fn) => fn(value));
      },
    };
  })(),
}));

vi.mock("$lib/stores/assistantChat.svelte.js", () => ({
  assistantChatStore: {
    subscribe: assistantState.subscribe,
    get value() { return { isOpen: true, conversationId: "conv-1", datasetReviewSessionId: "session-1", seedMessage: "", focusTarget: null }; },
  },
  closeAssistantChat: vi.fn(),
  setAssistantConversationId: vi.fn(),
  setAssistantSeedMessage: vi.fn(),
  setAssistantFocusTarget: vi.fn(),
}));

vi.mock("$app/navigation", () => ({ goto: vi.fn() }));
vi.mock("../../../../services/gitService.js", () => ({ gitService: { getDiff: vi.fn() } }));

const mockTranslations = {
  common: { error: "Common error" },
  assistant: {
    title: "Assistant",
    close: "Close",
    conversations: "Conversations",
    new: "New",
    active: "Active",
    archived: "Archived",
    more: "More",
    loading_history: "Loading history",
    loading_older: "Loading older",
    try_commands: "Try commands",
    sample_command_branch: "branch",
    sample_command_migration: "migration",
    sample_command_status: "status",
    you: "You",
    assistant: "Assistant",
    thinking: "Thinking",
    input_placeholder: "Type command",
    send: "Send",
    conversation: "Conversation",
    session_scope_title: "Active review context",
    session_scope_label: "Session",
    focus_target_label: "Focus",
    clear_focus_action: "Clear focus",
    states: { success: "Success" },
    open_task_drawer: "Open task drawer",
  },
  dataset_review: {
    clarification: {
      title: "Clarification queue",
      progress_label: "Progress",
      active_question_label: "Active question",
      why_it_matters_label: "Why it matters",
      current_guess_label: "Current guess",
      topic_label: "Topic",
      custom_answer_label: "Custom answer",
      answer_action: "Answer",
      custom_answer_action: "Use custom answer",
      skip_action: "Skip",
      expert_review_action: "Expert review",
      completed: "No active clarification question remains.",
      resume_action: "Resume clarification",
      feedback_label: "Feedback",
      feedback_prompt: "Record whether the clarification result was useful.",
      feedback_up_action: "Thumbs up",
      feedback_down_action: "Thumbs down",
      messages: {
        saving: "Saving clarification answer...",
        saved: "Clarification answer saved.",
        resumed: "Clarification queue resumed.",
      },
    },
  },
  dashboard: {},
};

vi.mock('$lib/i18n/index.svelte.js', () => ({
  t: {
    subscribe: (fn) => {
      fn(mockTranslations);
      return () => {};
    },
  },
  getT: vi.fn(() => mockTranslations),
  _: vi.fn((key) => key),
}));

describe("AssistantChatPanel clarification integration", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    api.fetchApi.mockImplementation((endpoint) => {
      if (endpoint === "/dataset-orchestration/sessions/session-1/clarification") {
        return Promise.resolve({
          clarification_session: {
            clarification_session_id: "clarification-1",
            session_id: "session-1",
            status: "active",
            current_question_id: "question-1",
            resolved_count: 1,
            remaining_count: 2,
          },
          current_question: {
            question_id: "question-1",
            topic_ref: "profile.summary",
            question_text: "Which customer label should be used?",
            why_it_matters: "This label is shown to reviewers.",
            current_guess: "Customer name",
            options: [{ value: "Customer name", label: "Customer name", is_recommended: true }],
          },
        });
      }
      if (endpoint === "/dataset-orchestration/sessions/session-1") {
        return Promise.resolve({ session_id: "session-1", session_version: 4, version: 4, profile: { business_summary: "Updated summary" } });
      }
      return Promise.resolve(null);
    });
    requestApi.mockResolvedValue({
      clarification_state: {
        clarification_session: {
          clarification_session_id: "clarification-1",
          session_id: "session-1",
          status: "active",
          current_question_id: null,
          resolved_count: 2,
          remaining_count: 1,
        },
        current_question: null,
      },
      session: { session_id: "session-1", session_version: 4, version: 4 },
    });
  });

  it("renders clarification queue inside assistant and refreshes session after answering", async () => {
    render(AssistantChatPanel);

    expect(await screen.findByText("Clarification queue")).toBeTruthy();
    expect(screen.getByText("Which customer label should be used?")).toBeTruthy();
    expect(screen.getByText("This label is shown to reviewers.")).toBeTruthy();

    await fireEvent.click(screen.getByRole("button", { name: "Answer" }));

    await waitFor(() => {
      expect(requestApi).toHaveBeenCalledWith(
        "/dataset-orchestration/sessions/session-1/clarification/answers",
        "POST",
        expect.objectContaining({ question_id: "question-1", answer_kind: "selected", answer_value: "Customer name" }),
      );
    });

    await waitFor(() => {
      expect(api.fetchApi).toHaveBeenCalledWith("/dataset-orchestration/sessions/session-1");
      expect(setDatasetReviewSession).toHaveBeenCalled();
    });
  });
});
// #endregion AssistantClarificationIntegrationTest:Module
