import { join, parse } from 'node:path';
import { FORM_PREFIX } from "../../constants.js";
import { FormModel } from "./models/FormModel.js";
import { plugin } from "./plugin.js";
import * as defaultServices from "./services/index.js";
import { formsService } from "./services/localFormsService.js";
import { findPackageRoot } from "./vision.js";
import { devtoolContext } from "../nunjucks/context.js";
export const configureEnginePlugin = async ({
  formFileName,
  formFilePath,
  services,
  controllers,
  preparePageEventRequestOptions,
  onRequest,
  saveAndExit,
  ordnanceSurveyApiKey
} = {}, cache) => {
  let model;
  if (formFileName && formFilePath) {
    const definition = await getForm(join(formFilePath, formFileName));
    const {
      name
    } = parse(formFileName);
    const initialBasePath = `${FORM_PREFIX}${name}`;
    model = new FormModel(definition, {
      basePath: initialBasePath,
      ordnanceSurveyApiKey
    }, services, controllers);
  }
  return {
    plugin,
    options: {
      model,
      services: services ?? {
        // services for testing, else use the disk loader option for running this service locally
        ...defaultServices,
        formsService: await formsService()
      },
      controllers,
      cache: cache ?? 'session',
      nunjucks: {
        baseLayoutPath: 'dxt-devtool-baselayout.html',
        paths: [join(findPackageRoot(), 'src/server/devserver')] // custom layout to make it really clear this is not the same as the runner
      },
      viewContext: devtoolContext,
      preparePageEventRequestOptions,
      onRequest,
      baseUrl: 'http://localhost:3009',
      // always runs locally
      saveAndExit,
      ordnanceSurveyApiKey
    }
  };
};
export async function getForm(importPath) {
  const {
    ext
  } = parse(importPath);
  const attributes = {
    type: ext === '.json' ? 'json' : 'module'
  };
  const formImport = import(importPath, {
    with: attributes
  });
  const {
    default: definition
  } = await formImport;
  return definition;
}
//# sourceMappingURL=configureEnginePlugin.js.map