#!/usr/bin/env node
// Copyright 2025 The Manifold Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import {readFile} from 'node:fs/promises';
import {Command} from 'commander';

import {bundleFile} from '../lib/bundler.js';
import * as worker from '../lib/worker.js';
import * as exportModel from '../lib/export-model.js';

const program = new Command();
program.name('manifold-cad')
    .description('Compile a ManifoldCAD program into a mesh.')
    .argument('<infile.[js|ts]>', 'Input file')
    .argument('<outfile>', 'Output file')
    .option('--jscdn <string>', 'Fetch npm packages from a CDN', 'jsDelivr')

    // True means '--bundle' is implied by default, and '--no-bundle'
    // must be specified to disable bundling.
    .option('--no-bundle', 'Do not bundle input file before building model', true)
    .action(async(infile, outfile, options) => {
      // Choose an exporter.  It will throw if we cannot match the extension.
      exportModel.supports(outfile, true);

      // Build the model.
      let bundle = '';
      if (options.bundle) {
        bundle = await bundleFile(infile, {jsCDN: options.jscdn});
      } else {
        bundle = await readFile(infile, 'utf-8');
      }
      const doc = await worker.evaluate(bundle, {doNotBundle:true});

      // Convert it and write it to disk.
      await exportModel.writeFile(outfile, doc);
    });

program.parseAsync(process.argv);
