import type { PostSequenceItem } from "@/types/workflow";
import { normalizeSequenceItem } from "@/lib/context/sequence-templates";

/** Raw context text sent to AI — preview box content only. */
export function getSequenceContent(item: PostSequenceItem): string {
  return item.content.trim();
}

export function getPostDisplayLabel(
  post: PostSequenceItem | string,
  index: number,
): string {
  if (typeof post !== "string") {
    if (post.title?.trim()) return post.title;
    return getPostDisplayLabel(post.content, index);
  }

  const firstLine = post
    .split("\n")
    .map((line) => line.trim())
    .find(Boolean);
  if (!firstLine) return `Post ${index + 1}`;
  return firstLine.length > 56 ? `${firstLine.slice(0, 53)}…` : firstLine;
}

export function getPostPreviewSnippet(post: PostSequenceItem | string): string {
  if (typeof post !== "string" && post.summary?.trim()) {
    return post.summary;
  }

  const content = typeof post === "string" ? post : post.content;
  const lines = content
    .split("\n")
    .map((line) => line.trim())
    .filter(Boolean);
  const problemLine = lines.find(
    (line) =>
      line.toLowerCase().startsWith("problem:") ||
      line.toLowerCase() === "## problem",
  );
  if (problemLine) {
    if (problemLine.toLowerCase() === "## problem") {
      const idx = lines.indexOf(problemLine);
      const next = lines[idx + 1];
      if (next) return next.slice(0, 120);
    }
    return problemLine.replace(/^problem:\s*/i, "").slice(0, 120);
  }

  const storySection = content.match(/## Current Story\s*\n([\s\S]*?)(?=\n## |\n---|$)/i);
  if (storySection?.[1]) {
    return storySection[1].trim().slice(0, 120);
  }
  const second = lines[1] ?? lines[0] ?? "";
  return second.slice(0, 120);
}

type LegacyPost = Partial<PostSequenceItem> & {
  title?: string;
  problem?: string;
  impact?: string;
  hashtags?: string;
  tag?: string;
  description?: string;
};

function buildContentFromLegacy(post: LegacyPost): string {
  const lines: string[] = [];

  const heading = post.tag?.trim() || post.title?.trim();
  if (heading && !heading.startsWith("Post ")) {
    lines.push(heading);
  }

  const problem = post.problem?.trim() || post.description?.trim() || "";
  if (problem) {
    lines.push(`Problem: ${problem.replace(/^problem:\s*/i, "")}`);
  }

  const impact = post.impact?.trim() || "";
  if (impact) {
    if (impact.includes("\n")) {
      lines.push("Impact:", impact);
    } else {
      lines.push(`Impact: ${impact.replace(/^impact:\s*/i, "")}`);
    }
  }

  const hashtags = post.hashtags?.trim() || "";
  if (hashtags) {
    if (lines.length) lines.push("");
    lines.push(hashtags);
  }

  return lines.join("\n").trim();
}

export function migrateSequenceItem(post: LegacyPost, index = 0): PostSequenceItem {
  if (post.title && post.summary) {
    return normalizeSequenceItem(post, index);
  }

  const content =
    post.content?.trim() || buildContentFromLegacy(post) || "Problem:\n\nImpact:\n";

  return normalizeSequenceItem({ ...post, content }, index);
}
