// #region ReviewWorkspaceHelpers [C:2] [TYPE Module] [SEMANTICS dataset-review, helpers, derived, utils]
// @BRIEF Shared helper functions for the dataset review workspace.
// @RATIONALE Extracted from DatasetReviewWorkspace to reduce page script size per INV_7.

interface I18nTranslation {
  dataset_review?: {
    workspace?: Record<string, unknown>;
    preview?: Record<string, unknown>;
    launch?: Record<string, unknown>;
    [key: string]: unknown;
  };
  common?: {
    not_available?: string;
    [key: string]: unknown;
  };
  [key: string]: unknown;
}

interface Session {
  session_id?: string;
  dataset_ref?: string;
  readiness_state?: string;
  recommended_action?: string;
  previews?: unknown[];
  [key: string]: unknown;
}

interface Profile {
  dataset_name?: string;
  business_summary?: string;
  [key: string]: unknown;
}

interface FilterItem {
  display_name?: string;
  filter_name?: string;
  [key: string]: unknown;
}

interface ClarificationQuestion {
  question_id?: string;
  question_text?: string;
  [key: string]: unknown;
}

interface Payload {
  label?: string;
  target?: string;
  section?: string;
  prompt?: string;
  mode?: string;
  [key: string]: unknown;
}

interface MilestoneItem {
  key: string;
  label: string;
  state: "done" | "active" | "pending";
}

/**
 * Build import milestones for the workspace progress tracking.
 */
export function buildImportMilestones(
  t: I18nTranslation,
  intakeAcknowledgment: boolean | null | undefined,
  session: Session | null | undefined,
  importedFilters: FilterItem[],
  latestPreview: unknown,
  profile: Profile | null | undefined,
  findings: unknown[],
  currentWorkspaceState: string
): MilestoneItem[] {
  const recognizedDone = Boolean(intakeAcknowledgment || session?.dataset_ref);
  const filtersDone = importedFilters.length > 0;
  const variablesDone = Boolean(importedFilters.length || latestPreview);
  const semanticsDone = Boolean(profile?.business_summary || findings.length > 0);
  const importState = currentWorkspaceState === "importing";

  return [
    { key: "recognized", label: (t.dataset_review?.workspace as Record<string, unknown>)?.import_milestones?.recognized as string, state: recognizedDone ? "done" : importState ? "active" : "pending" },
    { key: "filters", label: (t.dataset_review?.workspace as Record<string, unknown>)?.import_milestones?.filters as string, state: filtersDone ? "done" : importState ? "active" : "pending" },
    { key: "variables", label: (t.dataset_review?.workspace as Record<string, unknown>)?.import_milestones?.variables as string, state: variablesDone ? "done" : importState ? "active" : "pending" },
    { key: "semantic_sources", label: (t.dataset_review?.workspace as Record<string, unknown>)?.import_milestones?.semantic_sources as string, state: semanticsDone ? "done" : importState ? "active" : "pending" },
    { key: "summary", label: (t.dataset_review?.workspace as Record<string, unknown>)?.import_milestones?.summary as string, state: semanticsDone ? "done" : importState ? "active" : "pending" },
  ];
}

/**
 * Build workspace launch blockers list.
 */
export function buildWorkspaceLaunchBlockers(
  t: I18nTranslation,
  session: Session | null | undefined,
  unresolvedBlockingFindingsCount: number,
  pendingApprovalMappingsCount: number,
  previewGateState: string
): string[] {
  if (!session) return [];
  const blockers: string[] = [];
  if (unresolvedBlockingFindingsCount > 0)
    blockers.push(`${(t.dataset_review?.workspace as Record<string, unknown>)?.launch_blockers?.blocking_findings as string || "Blocking findings"}: ${unresolvedBlockingFindingsCount}`);
  if (pendingApprovalMappingsCount > 0)
    blockers.push(`${(t.dataset_review?.workspace as Record<string, unknown>)?.launch_blockers?.mapping_approvals as string || "Mapping approvals"}: ${pendingApprovalMappingsCount}`);
  if (previewGateState !== "ready")
    blockers.push(`${(t.dataset_review?.workspace as Record<string, unknown>)?.launch_blockers?.preview_state as string || "SQL preview state"}: ${previewGateState}`);
  if (String(session.readiness_state || "") !== "run_ready")
    blockers.push(`${(t.dataset_review?.workspace as Record<string, unknown>)?.launch_blockers?.readiness as string || "Readiness"}: ${session.readiness_state || "unknown"}`);
  return blockers;
}

/**
 * Build assistant seed prompt from session context.
 * @RATIONALE Human-readable prompt in user's language helps the assistant provide relevant context.
 * Technical details (session_id, phase) are omitted — the assistant already has them via API context.
 */
export function buildAssistantSeedPrompt(
  t: I18nTranslation,
  session: Session | null | undefined,
  profile: Profile | null | undefined,
  workspaceLaunchBlockers: string[],
  clarificationCurrentQuestion: ClarificationQuestion | null | undefined,
  importedFilters: FilterItem[]
): string {
  if (!session) return "";
  const datasetName = profile?.dataset_name || session.dataset_ref || "датасет";
  const summary = profile?.business_summary || "";

  const parts: string[] = [];

  // Opening: what dataset we're reviewing
  parts.push(`Я начинаю review датасета "${datasetName}".`);

  // Business summary if available
  if (summary && summary !== `Review session initialized for ${session.dataset_ref}.`) {
    parts.push(`Описание: ${summary}`);
  }

  // Filters status
  if (importedFilters.length > 0) {
    const filterNames = importedFilters.slice(0, 3).map(f => f.display_name || f.filter_name).join(", ");
    const extra = importedFilters.length > 3 ? ` и ещё ${importedFilters.length - 3}` : "";
    parts.push(`Восстановлены фильтры из дашборда: ${filterNames}${extra}.`);
  }

  // Active clarification takes priority
  if (clarificationCurrentQuestion?.question_text) {
    parts.push(`Есть вопрос для уточнения: ${clarificationCurrentQuestion.question_text}`);
  }

  // Readiness hint
  const readiness = session.readiness_state || "";
  if (readiness === "review_ready") {
    parts.push("Датасет готов к проверке. Помоги мне понять, что нужно сделать дальше.");
  } else if (readiness === "recovery_required") {
    parts.push("Контекст восстановлен частично. Помоги разобраться, чего не хватает.");
  } else if (readiness === "run_ready") {
    parts.push("Датасет готов к запуску. Проверь, всё ли в порядке.");
  }

  return parts.join(" ");
}

/**
 * Build assistant context prompt for contextual queries.
 */
export function buildAssistantContextPrompt(t: I18nTranslation, payload: Payload): string {
  const label = payload?.label || payload?.target || "current item";
  const section = payload?.section || "workspace";
  const context = String(payload?.prompt || "").trim();
  const workspaceI18n = (t.dataset_review?.workspace as Record<string, unknown>)?.assistant_context as Record<string, string> || {};
  if (payload?.mode === "improve") {
    return `${workspaceI18n.improve_prefix || "Improve"} ${label}. ${workspaceI18n.section_label || "Section"}: ${section}.${context ? ` ${workspaceI18n.context_label || "Context"}: ${context}` : ""}`;
  }
  return `${workspaceI18n.ask_prefix || "Help review"} ${label}. ${workspaceI18n.section_label || "Section"}: ${section}.${context ? ` ${workspaceI18n.context_label || "Context"}: ${context}` : ""}`;
}

/**
 * Get workspace state label from i18n.
 */
export function getWorkspaceStateLabel(t: I18nTranslation, state: string): string {
  return ((t.dataset_review?.workspace as Record<string, unknown>)?.state as Record<string, string>)?.[state] || state;
}

/**
 * Get recommended action label from i18n.
 */
export function getRecommendedActionLabel(t: I18nTranslation, action: string): string {
  const normalized = String(action || "import_from_superset");
  return ((t.dataset_review?.workspace as Record<string, unknown>)?.actions as Record<string, string>)?.[normalized] || normalized;
}

/**
 * Get primary action CTA label.
 */
export function getPrimaryActionCtaLabel(t: I18nTranslation, session: Session | null | undefined): string {
  if (!session) return (t.dataset_review?.workspace as Record<string, unknown>)?.next_action_label as string;
  if (session.recommended_action === "resume_session") return (t.dataset_review?.workspace as Record<string, unknown>)?.resume_action as string;
  if (session.recommended_action === "generate_sql_preview") return (t.dataset_review?.preview as Record<string, unknown>)?.generate_action as string;
  if (session.recommended_action === "launch_dataset") return (t.dataset_review?.launch as Record<string, unknown>)?.launch_action as string;
  return (t.dataset_review?.workspace as Record<string, unknown>)?.next_action_label as string;
}

/**
 * Merge a single item into a collection by id key, replacing if exists.
 */
export function mergeCollectionItem(collection: unknown[] = [], item: Record<string, unknown> | null = null, idKey = "id"): unknown[] {
  if (!item) return collection;
  const itemId = item?.[idKey];
  if (!itemId) return collection;
  return collection.some((entry: unknown) => (entry as Record<string, unknown>)?.[idKey] === itemId)
    ? collection.map((entry: unknown) => ((entry as Record<string, unknown>)?.[idKey] === itemId ? { ...(entry as Record<string, unknown>), ...item } : entry))
    : [...collection, item];
}

/**
 * Stringify a value for display.
 */
export function stringifyValue(t: I18nTranslation, value: unknown): string {
  if (value === null || value === undefined || value === "") return t.common?.not_available || "N/A";
  if (typeof value === "string") return value;
  try { return JSON.stringify(value); } catch (_) { return String(value); }
}
// #endregion ReviewWorkspaceHelpers
