#!/usr/bin/env node
/**
 * configure.mjs — stamp site.config.json (the single source of identity) into
 * every engine config. Run after editing site.config.json:
 *
 *     node scripts/configure.mjs
 *
 * Writes:
 *   - app/src/config/site.json        (Astro theme reads this)
 *   - agents/config.json              (site identity + author + timezone)
 *   - astroagent.config.json          (name + url)
 *
 * Finishes by regenerating the agent catalog (agents/AGENTS.md + agents.json).
 */
import { readFileSync, writeFileSync, existsSync, mkdirSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";

const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const read = (p) => JSON.parse(readFileSync(resolve(root, p), "utf8"));
const write = (p, obj) => {
  const full = resolve(root, p);
  mkdirSync(dirname(full), { recursive: true });
  writeFileSync(full, JSON.stringify(obj, null, 2) + "\n");
  console.log("  wrote", p);
};
const slug = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");

const site = read("site.config.json");
console.log(`Configuring site: ${site.name} <${site.url}>`);

// 1) Astro theme
write("app/src/config/site.json", {
  name: site.name,
  url: site.url,
  description: site.description,
  tagline: site.tagline,
  language: site.language,
  author: site.author,
  social: site.social,
});

// 2) agents
if (existsSync(resolve(root, "agents/config.json"))) {
  const cp = read("agents/config.json");
  cp.site = { ...cp.site, url: site.url, name: site.name, topic: site.topic, audience: site.audience, language: site.language };
  cp.author = { ...(cp.author || {}), slug: site.author.slug, name: site.author.name };
  if (cp.paths) cp.paths.projectRoot = root; // this clone's absolute path, not comiida's
  if (cp.editorial) cp.editorial.timezone = site.timezone;
  if (cp.image && cp.image.credit) cp.image.credit.author = site.name;
  write("agents/config.json", cp);
}

// 3) astroagent
if (existsSync(resolve(root, "astroagent.config.json"))) {
  const aa = read("astroagent.config.json");
  aa.name = slug(site.name);
  aa.url = site.url;
  if (aa.ai) aa.ai.agentUser = `${slug(site.name)}-agent`;
  write("astroagent.config.json", aa);
}

// 4) agent catalog (AGENTS.md + agents.json reflect this clone's identity)
if (existsSync(resolve(root, "agents/catalog.mjs"))) {
  const { execFileSync } = await import("node:child_process");
  execFileSync("node", [resolve(root, "agents/catalog.mjs")], { stdio: "inherit" });
}

console.log("Done. Rebuild the site:  (cd app && npm run build)");
