import fs from "node:fs/promises";
import path from "node:path";
import { execFileSync } from "node:child_process";
import { fileURLToPath } from "node:url";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const rootDir = path.resolve(__dirname, "..");
const distDir = path.join(rootDir, "dist");

export async function generateReleaseNotes() {
  const manifest = JSON.parse(await fs.readFile(path.join(rootDir, "manifest.json"), "utf8"));
  const version = manifest.version;
  const summaryPath = path.join(distDir, `release-summary-v${version}.md`);

  await fs.mkdir(distDir, { recursive: true });

  const commits = readRecentCommits();
  const body = [
    `# Sensa Basic v${version}`,
    "",
    `Generated at ${new Date().toISOString()}`,
    "",
    "## Packaging checklist",
    "",
    "- Manifest parsed successfully",
    "- JavaScript syntax checked",
    "- Automated tests passed",
    "- Content bundle rebuilt",
    "",
    "## Recent commits",
    "",
    ...(commits.length ? commits : ["- No recent git commits available."]),
    ""
  ].join("\n");

  await fs.writeFile(summaryPath, body, "utf8");
  return summaryPath;
}

function readRecentCommits() {
  try {
    const output = execFileSync("git", ["log", "--pretty=format:- %h %s", "-n", "8"], {
      cwd: rootDir,
      encoding: "utf8",
      stdio: ["ignore", "pipe", "ignore"]
    }).trim();
    return output ? output.split("\n") : [];
  } catch (error) {
    return [];
  }
}

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  await generateReleaseNotes();
}
