#!/usr/bin/env node

// src/cli.ts
import { Command, CommanderError } from "commander";

// src/index.ts
import { spawn } from "child_process";
import * as path from "path";
import * as fs from "fs";
import { fileURLToPath } from "url";

// src/convert-options.generated.ts
function buildConvertOptions(cliOptions) {
  const convertOptions = {};
  if (cliOptions.outputDir) {
    convertOptions.outputDir = cliOptions.outputDir;
  }
  if (cliOptions.password) {
    convertOptions.password = cliOptions.password;
  }
  if (cliOptions.format) {
    convertOptions.format = cliOptions.format;
  }
  if (cliOptions.quiet) {
    convertOptions.quiet = true;
  }
  if (cliOptions.contentSafetyOff) {
    convertOptions.contentSafetyOff = cliOptions.contentSafetyOff;
  }
  if (cliOptions.keepLineBreaks) {
    convertOptions.keepLineBreaks = true;
  }
  if (cliOptions.replaceInvalidChars) {
    convertOptions.replaceInvalidChars = cliOptions.replaceInvalidChars;
  }
  if (cliOptions.useStructTree) {
    convertOptions.useStructTree = true;
  }
  if (cliOptions.tableMethod) {
    convertOptions.tableMethod = cliOptions.tableMethod;
  }
  if (cliOptions.readingOrder) {
    convertOptions.readingOrder = cliOptions.readingOrder;
  }
  if (cliOptions.markdownPageSeparator) {
    convertOptions.markdownPageSeparator = cliOptions.markdownPageSeparator;
  }
  if (cliOptions.textPageSeparator) {
    convertOptions.textPageSeparator = cliOptions.textPageSeparator;
  }
  if (cliOptions.htmlPageSeparator) {
    convertOptions.htmlPageSeparator = cliOptions.htmlPageSeparator;
  }
  if (cliOptions.imageOutput) {
    convertOptions.imageOutput = cliOptions.imageOutput;
  }
  if (cliOptions.imageFormat) {
    convertOptions.imageFormat = cliOptions.imageFormat;
  }
  if (cliOptions.imageDir) {
    convertOptions.imageDir = cliOptions.imageDir;
  }
  if (cliOptions.pages) {
    convertOptions.pages = cliOptions.pages;
  }
  if (cliOptions.hybrid) {
    convertOptions.hybrid = cliOptions.hybrid;
  }
  if (cliOptions.hybridMode) {
    convertOptions.hybridMode = cliOptions.hybridMode;
  }
  if (cliOptions.hybridUrl) {
    convertOptions.hybridUrl = cliOptions.hybridUrl;
  }
  if (cliOptions.hybridTimeout) {
    convertOptions.hybridTimeout = cliOptions.hybridTimeout;
  }
  if (cliOptions.hybridFallback) {
    convertOptions.hybridFallback = true;
  }
  return convertOptions;
}
function buildArgs(options) {
  const args = [];
  if (options.outputDir) {
    args.push("--output-dir", options.outputDir);
  }
  if (options.password) {
    args.push("--password", options.password);
  }
  if (options.format) {
    if (Array.isArray(options.format)) {
      if (options.format.length > 0) {
        args.push("--format", options.format.join(","));
      }
    } else {
      args.push("--format", options.format);
    }
  }
  if (options.quiet) {
    args.push("--quiet");
  }
  if (options.contentSafetyOff) {
    if (Array.isArray(options.contentSafetyOff)) {
      if (options.contentSafetyOff.length > 0) {
        args.push("--content-safety-off", options.contentSafetyOff.join(","));
      }
    } else {
      args.push("--content-safety-off", options.contentSafetyOff);
    }
  }
  if (options.keepLineBreaks) {
    args.push("--keep-line-breaks");
  }
  if (options.replaceInvalidChars) {
    args.push("--replace-invalid-chars", options.replaceInvalidChars);
  }
  if (options.useStructTree) {
    args.push("--use-struct-tree");
  }
  if (options.tableMethod) {
    args.push("--table-method", options.tableMethod);
  }
  if (options.readingOrder) {
    args.push("--reading-order", options.readingOrder);
  }
  if (options.markdownPageSeparator) {
    args.push("--markdown-page-separator", options.markdownPageSeparator);
  }
  if (options.textPageSeparator) {
    args.push("--text-page-separator", options.textPageSeparator);
  }
  if (options.htmlPageSeparator) {
    args.push("--html-page-separator", options.htmlPageSeparator);
  }
  if (options.imageOutput) {
    args.push("--image-output", options.imageOutput);
  }
  if (options.imageFormat) {
    args.push("--image-format", options.imageFormat);
  }
  if (options.imageDir) {
    args.push("--image-dir", options.imageDir);
  }
  if (options.pages) {
    args.push("--pages", options.pages);
  }
  if (options.hybrid) {
    args.push("--hybrid", options.hybrid);
  }
  if (options.hybridMode) {
    args.push("--hybrid-mode", options.hybridMode);
  }
  if (options.hybridUrl) {
    args.push("--hybrid-url", options.hybridUrl);
  }
  if (options.hybridTimeout) {
    args.push("--hybrid-timeout", options.hybridTimeout);
  }
  if (options.hybridFallback) {
    args.push("--hybrid-fallback");
  }
  return args;
}

// src/index.ts
var __filename = fileURLToPath(import.meta.url);
var __dirname = path.dirname(__filename);
var JAR_NAME = "opendataloader-pdf-cli.jar";
function executeJar(args, executionOptions = {}) {
  const { streamOutput = false } = executionOptions;
  return new Promise((resolve, reject) => {
    const jarPath = path.join(__dirname, "..", "lib", JAR_NAME);
    if (!fs.existsSync(jarPath)) {
      return reject(
        new Error(`JAR file not found at ${jarPath}. Please run the build script first.`)
      );
    }
    const command = "java";
    const commandArgs = ["-jar", jarPath, ...args];
    const javaProcess = spawn(command, commandArgs);
    let stdout = "";
    let stderr = "";
    javaProcess.stdout.on("data", (data) => {
      const chunk = data.toString();
      if (streamOutput) {
        process.stdout.write(chunk);
      }
      stdout += chunk;
    });
    javaProcess.stderr.on("data", (data) => {
      const chunk = data.toString();
      if (streamOutput) {
        process.stderr.write(chunk);
      }
      stderr += chunk;
    });
    javaProcess.on("close", (code) => {
      if (code === 0) {
        resolve(stdout);
      } else {
        const errorOutput = stderr || stdout;
        const error = new Error(
          `The opendataloader-pdf CLI exited with code ${code}.

${errorOutput}`
        );
        reject(error);
      }
    });
    javaProcess.on("error", (err) => {
      if (err.message.includes("ENOENT")) {
        reject(
          new Error(
            "'java' command not found. Please ensure Java is installed and in your system's PATH."
          )
        );
      } else {
        reject(err);
      }
    });
  });
}
function convert(inputPaths, options = {}) {
  const inputList = Array.isArray(inputPaths) ? inputPaths : [inputPaths];
  if (inputList.length === 0) {
    return Promise.reject(new Error("At least one input path must be provided."));
  }
  for (const input of inputList) {
    if (!fs.existsSync(input)) {
      return Promise.reject(new Error(`Input file or folder not found: ${input}`));
    }
  }
  const args = [...inputList, ...buildArgs(options)];
  return executeJar(args, {
    streamOutput: !options.quiet
  });
}

// src/cli-options.generated.ts
function registerCliOptions(program) {
  program.option("-o, --output-dir <value>", "Directory where output files are written. Default: input file directory");
  program.option("-p, --password <value>", "Password for encrypted PDF files");
  program.option("-f, --format <value>", "Output formats (comma-separated). Values: json, text, html, pdf, markdown, markdown-with-html, markdown-with-images. Default: json");
  program.option("-q, --quiet", "Suppress console logging output");
  program.option("--content-safety-off <value>", "Disable content safety filters. Values: all, hidden-text, off-page, tiny, hidden-ocg");
  program.option("--keep-line-breaks", "Preserve original line breaks in extracted text");
  program.option("--replace-invalid-chars <value>", "Replacement character for invalid/unrecognized characters. Default: space");
  program.option("--use-struct-tree", "Use PDF structure tree (tagged PDF) for reading order and semantic structure");
  program.option("--table-method <value>", "Table detection method. Values: default (border-based), cluster (border + cluster). Default: default");
  program.option("--reading-order <value>", "Reading order algorithm. Values: off, xycut. Default: xycut");
  program.option("--markdown-page-separator <value>", "Separator between pages in Markdown output. Use %page-number% for page numbers. Default: none");
  program.option("--text-page-separator <value>", "Separator between pages in text output. Use %page-number% for page numbers. Default: none");
  program.option("--html-page-separator <value>", "Separator between pages in HTML output. Use %page-number% for page numbers. Default: none");
  program.option("--image-output <value>", "Image output mode. Values: off (no images), embedded (Base64 data URIs), external (file references). Default: external");
  program.option("--image-format <value>", "Output format for extracted images. Values: png, jpeg. Default: png");
  program.option("--image-dir <value>", "Directory for extracted images");
  program.option("--pages <value>", 'Pages to extract (e.g., "1,3,5-7"). Default: all pages');
  program.option("--hybrid <value>", "Hybrid backend for AI processing. Values: off (default), docling (docling-fast is deprecated alias)");
  program.option("--hybrid-mode <value>", "Hybrid triage mode. Values: auto (default, dynamic triage), full (skip triage, all pages to backend)");
  program.option("--hybrid-url <value>", "Hybrid backend server URL (overrides default)");
  program.option("--hybrid-timeout <value>", "Hybrid backend request timeout in milliseconds. Default: 30000");
  program.option("--hybrid-fallback", "Fallback to Java processing on hybrid backend error. Default: true");
}

// src/cli.ts
function createProgram() {
  const program = new Command();
  program.name("opendataloader-pdf").usage("[options] <input...>").description("Convert PDFs using the OpenDataLoader CLI.").showHelpAfterError("Use '--help' to see available options.").showSuggestionAfterError(false).argument("<input...>", "Input files or directories to convert");
  registerCliOptions(program);
  program.configureOutput({
    writeErr: (str) => {
      console.error(str.trimEnd());
    },
    outputError: (str, write) => {
      write(str);
    }
  });
  return program;
}
async function main() {
  const program = createProgram();
  program.exitOverride();
  try {
    program.parse(process.argv);
  } catch (err) {
    if (err instanceof CommanderError) {
      if (err.code === "commander.helpDisplayed") {
        return 0;
      }
      return err.exitCode ?? 1;
    }
    const message = err instanceof Error ? err.message : String(err);
    console.error(message);
    console.error("Use '--help' to see available options.");
    return 1;
  }
  const cliOptions = program.opts();
  const inputPaths = program.args;
  const convertOptions = buildConvertOptions(cliOptions);
  try {
    const output = await convert(inputPaths, convertOptions);
    if (output && !convertOptions.quiet) {
      process.stdout.write(output);
      if (!output.endsWith("\n")) {
        process.stdout.write("\n");
      }
    }
    return 0;
  } catch (err) {
    const message = err instanceof Error ? err.message : String(err);
    console.error(message);
    return 1;
  }
}
main().then((code) => {
  if (code !== 0) {
    process.exit(code);
  }
});
//# sourceMappingURL=cli.js.map