export type A2uiArtifactType =
  | 'form'
  | 'review'
  | 'chart'
  | 'import_wizard';

export type A2uiArtifactStatus = 'rendering' | 'pending' | 'submitted' | 'expired' | 'cancelled';

export interface A2uiArtifact<T = unknown> {
  id: string;
  type: A2uiArtifactType;
  status: A2uiArtifactStatus;
  messageId: number;
  conversationId: number;
  payload: T;
  createdAt?: string | null;
  submittedAt?: string | null;
  supersededBy?: string | null;
}

const A2UI_ARTIFACT_TYPES = new Set<A2uiArtifactType>([
  'form',
  'review',
  'chart',
  'import_wizard',
]);

/**
 * 构造统一的 A2UI artifact 载荷，供 `ui.artifact` SSE 事件与前端归一化。
 */
export function buildA2uiArtifact<T>(input: {
  type: A2uiArtifactType;
  id: string;
  status: A2uiArtifactStatus;
  messageId: number;
  conversationId: number;
  payload: T;
  createdAt?: string | null;
  submittedAt?: string | null;
  supersededBy?: string | null;
}): A2uiArtifact<T> {
  if (!A2UI_ARTIFACT_TYPES.has(input.type)) {
    throw new Error(`未知 A2UI artifact 类型: ${String(input.type)}`);
  }
  return {
    id: input.id,
    type: input.type,
    status: input.status,
    messageId: input.messageId,
    conversationId: input.conversationId,
    payload: input.payload,
    ...(input.createdAt !== undefined ? { createdAt: input.createdAt } : {}),
    ...(input.submittedAt !== undefined ? { submittedAt: input.submittedAt } : {}),
    ...(input.supersededBy !== undefined ? { supersededBy: input.supersededBy } : {}),
  };
}
