import { spawnSync } from "node:child_process";

import { BREW_FALLBACK_PATHS, PANDOC_FALLBACK_PATHS, resolveExecutable } from "../system/executables.js";

export type PreviewSetupResult =
	| { status: "ready"; message: string }
	| { status: "installed"; message: string }
	| { status: "manual"; message: string };

export function setupPreviewDependencies(): PreviewSetupResult {
	const pandocPath = resolveExecutable("pandoc", PANDOC_FALLBACK_PATHS);
	if (pandocPath) {
		return { status: "ready", message: `pandoc already installed at ${pandocPath}` };
	}

	const brewPath = resolveExecutable("brew", BREW_FALLBACK_PATHS);
	if (process.platform === "darwin" && brewPath) {
		const result = spawnSync(brewPath, ["install", "pandoc"], { stdio: "inherit" });
		if (result.status !== 0) {
			throw new Error("Failed to install pandoc via Homebrew.");
		}
		return { status: "installed", message: "Preview dependency installed: pandoc" };
	}

	return {
		status: "manual",
		message: "pandoc is required for preview support. Install it manually and rerun `feynman --doctor`.",
	};
}
