import { promises as fs } from "node:fs";

import type { ContentItem } from "../content/types";

type InstagramPostsFile = {
  posts: Array<{
    url: string;
    title?: string;
    publishedAt?: string;
    thumbnailUrl?: string;
  }>;
};

export async function readInstagramEmbedPosts(filePath: string): Promise<ContentItem[]> {
  const raw = await fs.readFile(filePath, "utf8");
  const parsed = JSON.parse(raw) as InstagramPostsFile;
  const now = new Date().toISOString();
  const posts = Array.isArray(parsed.posts) ? parsed.posts : [];

  return posts
    .filter((p) => typeof p.url === "string" && p.url.length > 0)
    .map((p) => ({
      id: p.url,
      source: "instagram" as const,
      url: p.url,
      title: p.title || "Instagram post",
      // If the user doesn't provide a publish date, we still generate valid ISO-8601.
      // It won't be accurate, but it keeps the system functional until real ingestion is added.
      publishedAt: p.publishedAt ? new Date(p.publishedAt).toISOString() : now,
      thumbnailUrl: p.thumbnailUrl,
    }));
}
