import { Datex, datex } from "datex-core-legacy/no_init.ts";
import { getAppOptions } from "./src/app/config-files.ts";
import { getExistingFile } from "./src/utils/file-utils.ts";
import { command_line_options, enableTLS, login, template, init, rootPath, stage, watch_backend, live, reload } from "./src/app/args.ts";
import { normalizeAppOptions } from "./src/app/options.ts";
import { runLocal } from "./src/runners/run-local.ts";
import { runRemote } from "./src/runners/run-remote.ts";
import GitDeployPlugin from "./src/plugins/git-deploy.ts";
import LocalDockerRunner from "./src/runners/run-local-docker.ts";
import { triggerLogin } from "./src/utils/login.ts";
import { initBaseProject } from "./src/utils/init-base-project.ts";
import { CommandLineOptions } from "datex-core-legacy/utils/command-line-args/main.ts";
import { createProxyImports } from "./src/app/module-mapping.ts";
import { getDXConfigData } from "./src/app/dx-config-parser.ts";
import { Path } from "./src/utils/path.ts";
import { handleAutoUpdate, updateCache } from "./auto-update.ts";
import { StatusBar, StatusType } from "./src/utils/logging.ts";
import { addUIXNamespace } from "./src/base/uix-datex-module.ts";
import { enableUnhandledRejectionHandler } from "datex-core-legacy/utils/error-handling.ts";
import { enableErrorReporting } from "datex-core-legacy/utils/error-reporting.ts";
import { getErrorReportingPreference, saveErrorReportingPreference, shouldAskForErrorReportingPreference } from "./src/utils/error-reporting-preference.ts";
import { isCIRunner } from "./src/utils/check-ci.ts";
import { logger } from "./src/runners/runner.ts";
import { applyPlugins } from "./src/app/config-files.ts";
import { handleError } from "datex-core-legacy/utils/error-handling.ts";
if (StatusBar.clearScreen(), StatusBar.message = "Loading UIX...", StatusBar.status = StatusType.Loading, enableUnhandledRejectionHandler(logger), login && await triggerLogin(), void 0 != init ? (StatusBar.sideMessage = "Initializing Project", rootPath ? handleError("A UIX Project exists already in this location", logger) : await initBaseProject(init, template || void 0)) : '' === template && handleError("Please call UIX with the --init flag if you want to create a project from a template", logger), "dev" === stage) try {
    let allow = !1;
    await shouldAskForErrorReportingPreference() ? (allow = confirm("\nWould you like to share anonymized error reports with unyt.org to help improve UIX?"), await saveErrorReportingPreference(allow)) : await getErrorReportingPreference(), enableErrorReporting(allow);
} catch  {}
StatusBar.sideMessage = "Checking for UIX Updates";
let forceUpdate = !1, updatePromises = [];
if (await handleAutoUpdate(new Path(import.meta.url).parent_dir, "UIX")) {
    updatePromises.push(updateCache(import.meta.resolve("./run.ts")), updateCache(import.meta.resolve("./src/app/start.ts")), updateCache("https://cdn.unyt.org/uix/run.ts"));
    let { getJusix } = await import("./src/server/jusix.ts");
    updatePromises.push(getJusix(!0)), forceUpdate = !0;
}
StatusBar.sideMessage = "Checking for DATEX Updates", await handleAutoUpdate(new Path(import.meta.resolve("datex-core-legacy")).parent_dir, "DATEX Core") && (updatePromises.push(updateCache(import.meta.resolve("datex-core-legacy/datex.ts"))), forceUpdate = !0), StatusBar.sideMessage = "Waiting for Updates to Finish", await Promise.all(updatePromises), Datex.Logger.development_log_level = Datex.LOG_LEVEL.WARNING, Datex.Logger.production_log_level = Datex.LOG_LEVEL.DEFAULT;
let isWatching = live || watch_backend, params = {
    reload: forceUpdate || reload,
    enableTLS: enableTLS,
    inspect: command_line_options.option("inspect", {
        type: "string",
        description: "Enable debugging for the deno process"
    }),
    unstable: command_line_options.option("unstable", {
        type: "boolean",
        description: "Enable unstable deno features"
    }),
    detach: command_line_options.option("detach", {
        type: "boolean",
        aliases: [
            "d"
        ],
        default: !1,
        description: "Keep the app running in background"
    }),
    deno_config_path: getExistingFile(rootPath, './deno.json', './deno.jsonc')
};
async function loadPlugins() {
    let plugins = [
        new GitDeployPlugin()
    ], pluginDx = getExistingFile(rootPath, './plugins.dx');
    if (pluginDx) {
        let pluginData = await datex.get(pluginDx);
        for (let pluginUrl of ((pluginData instanceof URL || "string" == typeof pluginData) && (pluginData = [
            pluginData
        ]), pluginData instanceof Datex.Tuple && (pluginData = pluginData.toArray()), pluginData ?? [])){
            let pluginClass;
            try {
                pluginClass = (await import(pluginUrl.toString())).default;
            } catch  {
                logger.error(`Could not load plugin from ${pluginUrl}`);
                continue;
            }
            let plugin = new pluginClass();
            logger.debug(`Loaded plugin "${plugin.name}" (${pluginUrl})`);
            let existingPlugin = plugins.find((p)=>p.name === plugin.name);
            existingPlugin && (plugins.splice(plugins.indexOf(existingPlugin), 1), logger.warn(`Plugin "${plugin.name}" was overridden with ${pluginUrl}`)), plugins.push(plugin);
        }
    }
    return plugins;
}
CommandLineOptions.collecting && await CommandLineOptions.capture(), await addUIXNamespace(), StatusBar.sideMessage = "Loading Plugins";
let plugins = await loadPlugins(), runners = [
    new LocalDockerRunner()
], [options, new_base_url] = await normalizeAppOptions(await getAppOptions(rootPath), rootPath);
if (!options.import_map) throw Error("Could not find importmap");
async function runBackends(options) {
    if (!options.backend.length) {
        runLocal(params, new_base_url, options, isWatching);
        return;
    }
    for (let backend of options.backend)try {
        let { requiredLocation, stageEndpoint, domains, volumes, instances } = await getDXConfigData(backend, options);
        if (requiredLocation && requiredLocation !== Datex.LOCAL_ENDPOINT && !Deno.env.get("UIX_HOST_ENDPOINT")?.startsWith(requiredLocation?.toString())) {
            if ("string" == typeof requiredLocation) {
                let found = !1;
                for (let runner of runners)if (runner.name == requiredLocation) {
                    await runner.run({
                        params,
                        baseURL: new_base_url,
                        options,
                        backend,
                        endpoint: stageEndpoint,
                        domains,
                        volumes
                    }), found = !0;
                    break;
                }
                found || (logger.error(`UIX app runner for location "${requiredLocation}" not found`), Deno.exit(1));
            }
            requiredLocation instanceof Datex.Endpoint && runRemote(params, new_base_url, options, backend, requiredLocation, stageEndpoint, domains, volumes);
        } else {
            if (isCIRunner()) {
                let example = `
 ===================================
 use stage from # public.uix;

 location: stage {
     ${stage}: @+unyt_eu1
 }
 ===================================
`;
                new Datex.Logger().error("Cannot run the UIX app directly on the CI Runner.\n Make sure your .dx configuration is correct.\n The 'location' option for the '" + stage + "' stage must be a host endpoint, but is currently unset (defaults to local)\n Example .dx configuration: \n" + example), Deno.exit(1);
            }
            runLocal(params, new_base_url, options, isWatching);
        }
    } catch (e) {
        console.log(e);
    }
}
options.import_map = await createProxyImports(options, new_base_url, params.deno_config_path), StatusBar.sideMessage = "Applying Plugins", await applyPlugins(plugins, rootPath, options), StatusBar.sideMessage = "Starting Backend Instance(s)", await runBackends(options);

//# sourceMappingURL=./run.ts.map