import { existsSync, mkdirSync } from "node:fs";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";

const repoRoot = path.resolve(fileURLToPath(new URL("..", import.meta.url)));
const filterPath = path.join(repoRoot, "scripts", "pandoc-filters", "semantic-blocks.lua");
const preamblePath = path.join(repoRoot, "scripts", "pandoc-templates", "semantic-preamble.tex");

function usage() {
  console.error("Usage: node scripts/export-pdf.mjs <post.md> [--out output.pdf]");
}

function parseArgs(argv) {
  const args = [...argv];
  const input = args.find((arg) => !arg.startsWith("--"));
  const outIndex = args.indexOf("--out");
  const output = outIndex >= 0 ? args[outIndex + 1] : "";
  return { input, output };
}

const { input, output } = parseArgs(process.argv.slice(2));

if (!input) {
  usage();
  process.exit(2);
}

const inputPath = path.resolve(input);
if (!existsSync(inputPath)) {
  console.error(`Input file not found: ${inputPath}`);
  process.exit(2);
}

const outputPath = path.resolve(
  output || path.join(path.dirname(inputPath), `${path.basename(inputPath, path.extname(inputPath))}.pdf`),
);
mkdirSync(path.dirname(outputPath), { recursive: true });

const resourcePath = [path.dirname(inputPath), repoRoot].join(path.delimiter);

const pandocArgs = [
  inputPath,
  "--from",
  "markdown+fenced_code_attributes+tex_math_dollars+tex_math_single_backslash+footnotes+raw_html",
  "--resource-path",
  resourcePath,
  "--pdf-engine=lualatex",
  "--lua-filter",
  filterPath,
  "--include-in-header",
  preamblePath,
  "--output",
  outputPath,
];

const result = spawnSync("pandoc", pandocArgs, { stdio: "inherit" });

if (result.error?.code === "ENOENT") {
  console.error("pandoc is not installed or is not on PATH. Install pandoc and a LuaLaTeX distribution first.");
  process.exit(127);
}

if (result.status !== 0) {
  process.exit(result.status ?? 1);
}

console.log(`Wrote ${outputPath}`);
