const fs = require("fs");
const path = require("path");
const { buildManifestDocument } = require("./manifest-schema");

function writeScaffoldManifest(rootDir, report) {
  const capintDir = path.join(rootDir, ".capint");
  if (!fs.existsSync(capintDir)) fs.mkdirSync(capintDir, { recursive: true });

  const manifestPath = path.join(capintDir, "scaffold-manifest.json");
  let previous = null;
  if (fs.existsSync(manifestPath)) {
    try {
      previous = JSON.parse(fs.readFileSync(manifestPath, "utf-8"));
    } catch {
      previous = null;
    }
  }

  const manifest = buildManifestDocument({ report, previous });
  fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, "utf-8");
  return manifestPath;
}

function readScaffoldManifest(rootDir) {
  const manifestPath = path.join(rootDir, ".capint", "scaffold-manifest.json");
  if (!fs.existsSync(manifestPath)) return null;
  try {
    return JSON.parse(fs.readFileSync(manifestPath, "utf-8"));
  } catch {
    return null;
  }
}

module.exports = { writeScaffoldManifest, readScaffoldManifest };
