import { readFileSync, writeFileSync } from "node:fs";

/** Find the [ ... ] range of `export const <arrayName> = [ ... ]`. */
function blockRange(src, arrayName) {
  const marker = `export const ${arrayName} = [`;
  const start = src.indexOf(marker);
  if (start === -1) return null;
  const open = src.indexOf("[", start);
  let depth = 0;
  let i = open;
  for (; i < src.length; i++) {
    if (src[i] === "[") depth++;
    else if (src[i] === "]") {
      depth--;
      if (depth === 0) break;
    }
  }
  return { open, close: i };
}

function slugsIn(src, arrayName) {
  const r = blockRange(src, arrayName);
  if (!r) return new Set();
  const block = src.slice(r.open, r.close);
  const out = new Set();
  for (const m of block.matchAll(/slug:\s*["']([^"']+)["']/g)) out.add(m[1]);
  return out;
}

export function readSlugs(file) {
  const src = readFileSync(file, "utf8");
  return {
    authors: slugsIn(src, "authors"),
    categories: slugsIn(src, "categories"),
    tags: slugsIn(src, "tags"),
  };
}

/** Insert { slug, name } as the first element of the named array if slug is absent. */
export function ensureEntry(file, arrayName, slug, name) {
  let src = readFileSync(file, "utf8");
  if (slugsIn(src, arrayName).has(slug)) return false;
  const r = blockRange(src, arrayName);
  if (!r) throw new Error(`Array ${arrayName} not found in ${file}`);
  const entry = `\n  { slug: ${JSON.stringify(slug)}, name: ${JSON.stringify(name)} },`;
  src = src.slice(0, r.open + 1) + entry + src.slice(r.open + 1);
  writeFileSync(file, src);
  return true;
}

/** Insert a full author object if the slug is absent. author = {slug,name,bio,longBio,avatar} */
export function ensureAuthor(file, author) {
  let src = readFileSync(file, "utf8");
  if (slugsIn(src, "authors").has(author.slug)) return false;
  const r = blockRange(src, "authors");
  if (!r) throw new Error(`authors array not found in ${file}`);
  const obj =
    `\n  {\n` +
    `    slug: ${JSON.stringify(author.slug)},\n` +
    `    name: ${JSON.stringify(author.name)},\n` +
    `    bio: ${JSON.stringify(author.bio || "")},\n` +
    `    longBio: ${JSON.stringify(author.longBio || author.bio || "")},\n` +
    `    avatar: ${JSON.stringify(author.avatar || "")},\n` +
    `  },`;
  src = src.slice(0, r.open + 1) + obj + src.slice(r.open + 1);
  writeFileSync(file, src);
  return true;
}
