import type { ArticleInput, ImageInput, PublishPlatform } from "../domain/types";
import { articleInputSchema } from "../domain/validation";

export interface RawArticleInput {
  title: string;
  body: string;
  image_lines?: string;
  images?: ImageInput[];
  platform: PublishPlatform;
  user_instructions?: string;
}

export function normalizeInput(input: RawArticleInput) {
  const images =
    input.images ??
    (input.image_lines ?? "")
      .split(/\r?\n/)
      .map((line) => line.trim())
      .filter(Boolean)
      .map<ImageInput>((content) => ({
        type: /^https?:\/\//i.test(content) ? "link" : "description",
        content,
      }));

  const articleInput = articleInputSchema.parse({
    title: input.title,
    body: input.body,
    images,
    platform: input.platform,
    user_instructions: input.user_instructions ?? "",
  });

  return {
    article_draft: {
      title: articleInput.title,
      body: normalizeBody(articleInput.body),
    },
    image_assets: articleInput.images,
    publish_context: {
      platform: articleInput.platform,
      user_instructions: articleInput.user_instructions,
    },
    articleInput: {
      ...articleInput,
      body: normalizeBody(articleInput.body),
    } satisfies ArticleInput,
  };
}

function normalizeBody(body: string) {
  return body
    .split(/\r?\n/)
    .map((line) => line.trim())
    .join("\n")
    .replace(/\n{3,}/g, "\n\n")
    .trim();
}
