import fs from "node:fs";
import path from "node:path";
import { runMdschema } from "../../mdschema";
import { type CommandResult, success, silentFailure } from "./command-result";

export async function runGenerateDoc(
  outputPath: string,
  schemaPath: string,
  cwd: string,
): Promise<CommandResult> {
  const absoluteOutput = path.resolve(cwd, outputPath);

  if (fs.existsSync(absoluteOutput)) {
    console.error(`File already exists: ${outputPath}`);
    return silentFailure();
  }

  try {
    fs.mkdirSync(path.dirname(absoluteOutput), { recursive: true });
  } catch (err) {
    console.error(
      `Failed to create directory: ${err instanceof Error ? err.message : String(err)}`,
    );
    return silentFailure();
  }

  const { exitCode, stdout, stderr } = await runMdschema(
    ["generate", "--schema", schemaPath, "--output", absoluteOutput],
    cwd,
  );

  if (stdout.trim()) console.log(stdout);
  if (stderr.trim()) console.error(stderr);

  return exitCode === 0 ? success() : silentFailure(exitCode);
}
