import type {
  ArticleCaseInputPayload,
  HumanCopyCaseInputPayload,
  ProcessSummaryStep,
} from "./types";

export function excerpt(value: string, maxLength = 120) {
  const compact = value.replace(/\s+/g, " ").trim();
  return compact.length > maxLength
    ? `${compact.slice(0, maxLength)}…`
    : compact;
}

export function buildArticleCaseSummary(
  input: Pick<
    ArticleCaseInputPayload,
    "source_title" | "source_body" | "publish_platform"
  >,
) {
  const sourceExcerpt = excerpt(input.source_body);
  return {
    title: input.source_title.trim() || excerpt(input.source_body, 32),
    summary: sourceExcerpt,
    publish_target: input.publish_platform,
    source_excerpt: sourceExcerpt,
  };
}

export function buildHumanCopyCaseSummary(input: HumanCopyCaseInputPayload) {
  const publishTarget = input.publish_target.trim() || "未指定";
  const sourceExcerpt = excerpt(input.source_text);
  return {
    title: `人味文案优化：${publishTarget}`,
    summary: sourceExcerpt,
    publish_target: publishTarget,
    source_excerpt: sourceExcerpt,
  };
}

export function createProcessStep({
  stage,
  startedAt,
  endedAt,
  status,
  errorSummary,
  rewriteRound,
  producedResultVersion,
}: {
  stage: string;
  startedAt: number;
  endedAt: number;
  status: ProcessSummaryStep["status"];
  errorSummary?: string;
  rewriteRound?: number;
  producedResultVersion: boolean;
}): ProcessSummaryStep {
  return {
    stage,
    started_at: new Date(startedAt).toISOString(),
    ended_at: new Date(endedAt).toISOString(),
    duration_ms: Math.max(0, endedAt - startedAt),
    status,
    ...(errorSummary ? { error_summary: errorSummary } : {}),
    ...(rewriteRound ? { rewrite_round: rewriteRound } : {}),
    produced_result_version: producedResultVersion,
  };
}
