/**
 * @vitest-environment jsdom
 */
// @ts-nocheck
// #region DatasetReviewWorkspaceUxTests:Module [TYPE Function]
// @SEMANTICS: dataset-review, workspace, route, ux-tests, review-state, chat-centric, execution-rail
// @PURPOSE: Verify the `027` dataset review workspace keeps assistant chat as the primary surface while preserving execution rail and resumable intake behavior.
// @LAYER UI
// @RELATION DEPENDS_ON -> [DatasetReviewWorkspace]
// @UX_STATE: Empty -> Intake-first workspace renders clear starting actions.
// @UX_STATE: Importing -> Progressive milestones remain visible while review context is assembled.
// @UX_STATE: Review -> Workspace exposes left context rail, embedded assistant center, and right execution rail.

import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, waitFor, fireEvent } from "@testing-library/svelte";
import DatasetReviewWorkspace from "../+page.svelte";
import { api } from "$lib/api.js";

const { mockedGoto } = vi.hoisted(() => ({ mockedGoto: vi.fn() }));
const mockedPage = vi.mocked(await import("$app/state")).page;
const routeState = mockedPage.params;

function createSessionDetail(overrides = {}) {
  return {
    session_id: "session-1",
    session_version: 3,
    version: 3,
    environment_id: "env-1",
    source_kind: "superset_link",
    source_input: "https://superset.local/dashboard/10",
    dataset_ref: "public.sales",
    readiness_state: "partially_ready",
    recommended_action: "review_documentation",
    status: "active",
    current_phase: "review",
    active_task_id: "task-77",
    findings: [
      {
        finding_id: "finding-1",
        title: "Missing semantic description",
        code: "SEM-1",
        area: "dataset_profile",
        severity: "warning",
        message: "Business summary needs confirmation",
        resolution_state: "open",
      },
      {
        finding_id: "finding-2",
        title: "Preview must be refreshed",
        code: "PREVIEW-1",
        area: "sql_preview",
        severity: "blocking",
        message: "Compiled SQL snapshot is stale",
        resolution_state: "open",
      },
    ],
    imported_filters: [
      {
        filter_id: "filter-1",
        filter_name: "region",
        display_name: "Region",
        source: "superset",
        confidence_state: "mostly_confirmed",
        recovery_status: "partial",
        normalized_value: ["EMEA"],
        raw_value: ["EMEA"],
      },
    ],
    execution_mappings: [
      {
        mapping_id: "mapping-1",
        variable_name: "region",
        approval_state: "pending",
        requires_explicit_approval: true,
      },
    ],
    previews: [
      {
        preview_id: "preview-1",
        preview_status: "ready",
        compiled_by: "superset",
        compiled_sql: "select * from sales where region = 'EMEA'",
        preview_fingerprint: "fp-1",
      },
    ],
    run_contexts: [
      {
        run_context_id: "run-1",
        launched_at: "2026-03-21T20:00:00Z",
      },
    ],
    profile: {
      dataset_name: "Sales Dataset",
      schema_name: "public",
      database_name: "analytics",
      business_summary_source: "imported",
      confidence_state: "mostly_confirmed",
      business_summary: "Imported business description",
    },
    clarification_sessions: [
      {
        clarification_session_id: "clarification-1",
        status: "active",
        current_question_id: "question-1",
        resolved_count: 1,
        remaining_count: 2,
      },
    ],
    ...overrides,
  };
}

function createClarificationState(overrides = {}) {
  return {
    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",
      clarification_session_id: "clarification-1",
      topic_ref: "profile.summary",
      question_text: "Which customer label should be used?",
      why_it_matters: "This label is shown to reviewers.",
    },
    ...overrides,
  };
}

vi.mock("$app/navigation", () => ({
  goto: mockedGoto,
}));

vi.mock("$app/state", () => ({
  page: {
    params: {
      id: "",
    },
  },
}));

vi.mock('$lib/i18n/index.svelte.js', () => ({
  t: {
    subscribe: (fn) => {
      fn({
        common: {
          error: "Common error",
        },
        assistant: {
          title: "AI Workspace",
          close: "Close",
          session_scope_title: "Active review context",
          session_scope_label: "Session",
          focus_target_label: "Focus",
          clear_focus_action: "Clear focus",
          clarification_banner_title: "Clarification queue is active",
          clarification_resume_action: "Resume",
          clarification_dismiss_action: "Dismiss",
          conversations: "Conversations",
          new: "New",
          active: "Active",
          archived: "Archived",
          more: "More",
          loading_history: "Loading history",
          loading_older: "Loading older",
          try_commands: "Start the review dialog from here.",
          sample_command_branch: "Review launch blockers",
          sample_command_migration: "Explain recovered filters",
          sample_command_status: "Check launch readiness",
          assistant: "Assistant",
          you: "You",
          thinking: "Thinking",
          send: "Send",
          input_placeholder: "Ask the assistant what should happen next",
          states: {
            success: "success",
            failed: "failed",
            needs_confirmation: "needs_confirmation",
          },
          task_id: "Task",
          open_task_drawer: "Open task",
          highlight_workspace_action: "Highlight in workspace",
          confirmation_card_title: "Confirmation required",
          confirmation_operation_label: "Action",
          confirmation_scope_fallback: "This action affects the current assistant scope.",
        },
        dashboard: {
          llm_not_configured: "LLM is not configured",
          llm_configure_provider: "Configure provider",
          llm_configure_key: "Configure key",
          llm_status_unavailable: "Status unavailable",
        },
        dataset_review: {
          source: {
            title: "Start dataset review",
            description: "Paste link or provide dataset reference.",
            recognized_link_hint: "Recognized Superset link",
            dataset_selection_acknowledged: "Dataset selection acknowledged",
            async_recovery_hint: "Recovery steps run async",
            submit_failed: "Submit failed",
            superset_link_placeholder: "https://superset.local/dashboard/10",
            submit_superset_link: "Start from link",
          },
          workspace: {
            eyebrow: "Dataset review",
            title: "Dataset review workspace",
            description: "Review imported dataset context.",
            state_label: "Workspace state",
            readiness_label: "Readiness",
            loading: "Loading workspace",
            load_failed: "Failed to load review session",
            resume_failed: "Failed to resume session",
            save_failed: "Failed to save session",
            export_failed: "Failed to export artifact",
            empty_state_title: "No session loaded",
            source_badge_fallback: "review session",
            save_session_action: "Save session",
            source_session_title: "Source & session",
            source_label: "Dataset source",
            import_status_title: "Superset import status",
            import_progress_eyebrow: "Import progress",
            import_progress_title: "Recovering dataset context progressively",
            import_progress_body: "The workspace reveals milestones as source, filters, variables, and semantic candidates become available.",
            import_milestones: {
              recognized: "Dataset recognized",
              filters: "Saved native filters recovered",
              variables: "Dataset template variables detected",
              semantic_sources: "Nearby semantic sources identified",
              summary: "Preliminary summary prepared",
            },
            summary_sources: {
              imported: "Imported",
              ai_draft: "AI draft",
            },
            confidence: {
              mostly_confirmed: "Mostly confirmed",
              unresolved: "Unresolved",
            },
            next_action_label: "Next action",
            next_action_card_eyebrow: "Recommended next step",
            phase_card_label: "Phase",
            preview_gate_card_label: "Preview gate",
            clarification_queue_card_label: "Clarification queue",
            launch_blockers_card_label: "Launch blockers",
            launch_blockers_title: "Launch blockers snapshot",
            filter_count_label: "Filters",
            mapping_count_label: "Mappings",
            finding_count_label: "Findings",
            clarification_focus_label: "Clarification focus",
            partial_recovery_notice:
              "The session is in partial recovery mode. Review and assistant guidance stay available, but launch remains blocked until blockers are resolved and a current SQL preview is ready.",
            recovered_filters_title: "Recovered filters",
            execution_rail_body:
              "The right rail stays dedicated to preview, blockers, exports, and launch so execution truth remains visible while the assistant stays primary.",
            launch_blockers: {
              blocking_findings: "Blocking findings",
              mapping_approvals: "Mapping approvals",
              preview_state: "SQL preview state",
              readiness: "Readiness",
            },
            assistant_context: {
              ask_prefix: "Help review",
              improve_prefix: "Improve",
              section_label: "Section",
              context_label: "Context",
            },
            exports_title: "Exports",
            exports_description: "Export review artifacts.",
            export_documentation_json: "Documentation JSON",
            export_documentation_markdown: "Documentation Markdown",
            export_validation_json: "Validation JSON",
            export_validation_markdown: "Validation Markdown",
            health_title: "Review health",
            actions: {
              review_documentation: "Review documentation",
              resume_session: "Resume session",
              launch_dataset: "Launch dataset",
              generate_sql_preview: "Generate SQL preview",
            },
            readiness: {
              empty: "Empty",
              partially_ready: "Partially ready",
              compiled_preview_ready: "Preview ready",
              run_ready: "Run ready",
            },
            state: {
              empty: "empty",
              importing: "importing",
              review: "review",
            },
          },
          findings: {
            blocking_title: "Blocking",
            warning_title: "Warnings",
            informational_title: "Info",
          },
          clarification: {
            title: "Resolve one ambiguity at a time",
            progress_label: "Progress",
            resume_action: "Resume clarification",
          },
          preview: {
            generate_action: "Generate preview",
          },
          launch: {
            launch_action: "Launch in SQL Lab",
          },
        },
      });
      return () => {};
    },
  },
}));

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

vi.mock("$lib/stores/datasetReviewSession.svelte.js", () => ({
  datasetReviewSessionStore: {
    subscribe: (run) => {
      run({ session: null });
      return () => {};
    },
  },
  setError: vi.fn(),
  setLoading: vi.fn(),
  setSession: vi.fn(),
  resetSession: vi.fn(),
}));

vi.mock("$lib/stores/environmentContext.svelte.js", () => ({
  environmentContextStore: {
    subscribe: (run) => {
      run({
        environments: [{ id: "env-1", name: "DEV" }],
        selectedEnvId: "env-1",
      });
      return () => {};
    },
  },
  initializeEnvironmentContext: vi.fn().mockResolvedValue(undefined),
}));

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

vi.mock("$lib/api/assistant.js", () => ({
  sendAssistantMessage: vi.fn(),
  confirmAssistantOperation: vi.fn(),
  cancelAssistantOperation: vi.fn(),
  getAssistantHistory: vi.fn().mockResolvedValue({
    items: [
      {
        message_id: "assistant-1",
        role: "assistant",
        text: "I recovered 1 filter and found 2 launch blockers.",
        state: "success",
        created_at: "2026-03-21T20:00:00Z",
        conversation_id: "conv-1",
        actions: [],
      },
    ],
    has_next: false,
    conversation_id: "conv-1",
  }),
  getAssistantConversations: vi.fn().mockResolvedValue({
    items: [
      {
        conversation_id: "conv-1",
        title: "Workspace review",
        last_message: "I recovered 1 filter and found 2 launch blockers.",
        updated_at: "2026-03-21T20:00:00Z",
      },
    ],
    has_next: false,
    active_total: 1,
    archived_total: 0,
  }),
  deleteAssistantConversation: vi.fn().mockResolvedValue({ success: true }),
}));

vi.mock("$lib/components/dataset-review/CompiledSQLPreview.svelte", () => ({
  default: vi.fn(() => null),
}));

vi.mock("$lib/components/dataset-review/LaunchConfirmationPanel.svelte", () => ({
  default: vi.fn(() => null),
}));

vi.mock("$lib/components/dataset-review/ValidationFindingsPanel.svelte", () => ({
  default: vi.fn(() => null),
}));

vi.mock("$lib/components/dataset-review/SemanticLayerReview.svelte", () => ({
  default: vi.fn(() => null),
}));

vi.mock("$lib/components/dataset-review/ExecutionMappingReview.svelte", () => ({
  default: vi.fn(() => null),
}));

describe("DatasetReviewWorkspace UX Contract", () => {
  beforeEach(() => {
    routeState.id = "";
    vi.clearAllMocks();
    api.fetchApi.mockReset();
    api.postApi.mockReset();
    mockedGoto.mockReset();
    api.getLlmStatus.mockResolvedValue({ configured: true, reason: "ok" });
  });

  it("empty_state_renders_source_intake", async () => {
    api.fetchApi.mockResolvedValue(undefined);

    render(DatasetReviewWorkspace);

    await waitFor(() => {
      expect(screen.getByText("Start dataset review")).toBeDefined();
    });

    expect(screen.getByText("Workspace state: empty")).toBeDefined();
    expect(screen.getByText("Paste link or provide dataset reference.")).toBeDefined();
  });

  it("import_submission_transitions_to_review_state", async () => {
    const createdSession = createSessionDetail();
    let resolveSessionLoad;
    let resolvePost;
    api.postApi.mockImplementation(() => new Promise((resolve) => { resolvePost = resolve; }));
    api.fetchApi.mockImplementation((url) => {
      if (url === "/dataset-orchestration/sessions/session-1") {
        return new Promise((resolve) => {
          resolveSessionLoad = resolve;
        });
      }
      if (url === "/dataset-orchestration/sessions/session-1/clarification") {
        return Promise.resolve(createClarificationState());
      }
      return Promise.resolve(undefined);
    });

    render(DatasetReviewWorkspace);

    await waitFor(() => {
      expect(screen.getByText("Start dataset review")).toBeDefined();
    });

    const sourceInput = screen.getByPlaceholderText("https://superset.local/dashboard/10");

    await fireEvent.input(sourceInput, {
      target: { value: "https://superset.local/dashboard/10" },
    });
    // Submit the form directly — fireEvent.click on a submit button may not
    // trigger the form's onsubmit event in jsdom.
    const form = sourceInput.closest("form");
    await fireEvent.submit(form);

    await waitFor(() => {
      expect(screen.getByText("Workspace state: importing")).toBeDefined();
    });

    resolvePost({ session_id: "session-1" });

    await waitFor(() => {
      expect(mockedGoto).toHaveBeenCalledWith("/datasets/review/session-1");
    });

    resolveSessionLoad(createdSession);
  });

  it("review_state_uses_chat_centric_three_column_layout", async () => {
    routeState.id = "session-1";
    api.fetchApi
      .mockResolvedValueOnce(createSessionDetail())
      .mockResolvedValueOnce(createClarificationState());

    render(DatasetReviewWorkspace);

    await waitFor(() => {
      expect(screen.getByTestId("workspace-chat-layout")).toBeDefined();
    });

    expect(screen.getByText("AI Workspace")).toBeDefined();
    expect(screen.getByText("Source & session")).toBeDefined();
    expect(screen.getByText("Launch blockers snapshot")).toBeDefined();
    expect(screen.getByText("Exports")).toBeDefined();
    expect(screen.queryByText("Review semantic field values")).toBeNull();
    expect(screen.queryByText("Findings")).toBeNull();
  });

  it("embedded_assistant_receives_session_scoped_seed_context", async () => {
    routeState.id = "session-1";
    const assistantStoreModule = await import("$lib/stores/assistantChat.svelte.js");
    api.fetchApi
      .mockResolvedValueOnce(createSessionDetail())
      .mockResolvedValueOnce(createClarificationState());

    render(DatasetReviewWorkspace);

    await waitFor(() => {
      expect(screen.getByText("AI Workspace")).toBeDefined();
    });

    expect(assistantStoreModule.setAssistantDatasetReviewSessionId).toHaveBeenCalledWith(
      "session-1",
    );
    expect(assistantStoreModule.setAssistantSeedMessage).toHaveBeenCalled();
  });

  it("right_execution_rail_keeps_exports_and_health_visible", async () => {
    routeState.id = "session-1";
    api.fetchApi
      .mockResolvedValueOnce(createSessionDetail())
      .mockResolvedValueOnce(createClarificationState())
      .mockResolvedValueOnce({
        artifact_type: "documentation",
        format: "json",
        storage_ref: "artifacts/doc.json",
      });

    render(DatasetReviewWorkspace);

    await waitFor(() => {
      expect(screen.getByText("Exports")).toBeDefined();
    });

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

    await waitFor(() => {
      expect(api.fetchApi).toHaveBeenCalledWith(
        "/dataset-orchestration/sessions/session-1/exports/documentation?format=json",
      );
    });

    expect(screen.getByText("Review health")).toBeDefined();
    expect(screen.getByText("Launch blockers snapshot")).toBeDefined();
  });
});
