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

import type { ContentCache } from "./types";

const DEFAULT_CACHE: ContentCache = {
  generatedAt: new Date(0).toISOString(),
  items: [],
  wordpress: { posts: [], pages: [], categories: [] },
};

function getCachePath() {
  // Read from the repo-local content cache (populated by scripts/fetch-content.ts).
  return path.join(process.cwd(), "content", "cache", "content.json");
}

export async function readContentCache(): Promise<ContentCache> {
  const cachePath = getCachePath();
  try {
    const raw = await fs.readFile(cachePath, "utf8");
    const parsed = JSON.parse(raw) as ContentCache;
    if (!parsed || !Array.isArray(parsed.items) || typeof parsed.generatedAt !== "string") {
      return DEFAULT_CACHE;
    }
    // Ensure new optional fields exist (keeps callers simple).
    if (!parsed.wordpress) {
      parsed.wordpress = { posts: [], pages: [], categories: [] };
    }
    return parsed;
  } catch {
    // Cache missing is normal for first run.
    return DEFAULT_CACHE;
  }
}
