import type {
  AiArtifactSchema,
  AiChartSchema,
  AiChatMessage,
  AiFormSchema,
  AiReviewSchema,
} from './types';

export function mergeById<T extends { id: string }>(
  current: T[] | undefined,
  incoming: T | T[] | undefined,
): T[] {
  const items = Array.isArray(incoming) ? incoming : incoming ? [incoming] : [];
  if (!items.length) return current ?? [];
  const next = [...(current ?? [])];
  for (const item of items) {
    if (!item || typeof item !== 'object') continue;
    const index = next.findIndex((existing) => existing.id === item.id);
    if (index === -1) {
      next.push(item);
    } else {
      next[index] = item;
    }
  }
  return next;
}

export function mergeForms(
  current: AiFormSchema[] | undefined,
  incoming: AiFormSchema | AiFormSchema[] | undefined,
): AiFormSchema[] {
  const items = Array.isArray(incoming) ? incoming : incoming ? [incoming] : [];
  if (!items.length) return current ?? [];
  const next = [...(current ?? [])];
  for (const item of items) {
    if (item && typeof item === 'object' && !next.some((existing) => existing.id === item.id)) {
      next.push(item);
    }
  }
  return next;
}

function payloadOf(artifact: AiArtifactSchema): unknown {
  return artifact.payload && typeof artifact.payload === 'object' ? artifact.payload : {};
}

/**
 * 将统一 artifact 归入 uiArtifacts，并按类型派发到 legacy 列表。
 * payload 来自服务端契约（表单/审阅/图表/预检/向导），按类型做单次断言。
 */
export function mergeArtifactIntoMessage(
  message: AiChatMessage,
  artifact: AiArtifactSchema,
): AiChatMessage {
  message.uiArtifacts = mergeById<AiArtifactSchema>(message.uiArtifacts, artifact);
  const payload = payloadOf(artifact);
  if (artifact.type === 'form') {
    message.forms = mergeForms(message.forms, payload as AiFormSchema);
  } else if (artifact.type === 'review') {
    message.reviews = mergeById<AiReviewSchema>(message.reviews, payload as AiReviewSchema);
  } else if (artifact.type === 'chart') {
    message.charts = mergeById<AiChartSchema>(message.charts, payload as AiChartSchema);
  } else if (artifact.type === 'import_wizard') {
    message.metadata = { ...message.metadata, a2uiImportWizard: payload };
  }
  return message;
}
