#!/usr/bin/env node
import { existsSync, readFileSync } from "node:fs";
import { toolInfoOptionsFromConfig } from "@galaxy-tool-util/core";
import { loadWorkflowToolConfig } from "@galaxy-tool-util/core/node";
import { createApp } from "../app.js";
const args = process.argv.slice(2);
let directory = null;
let host = "127.0.0.1";
let port = 8000;
let cacheDir;
let configPath;
let outputSchema = false;
const extraConnectSrc = [];
for (let i = 0; i < args.length; i++) {
    if (args[i] === "--host" && args[i + 1]) {
        host = args[++i];
    }
    else if (args[i] === "--port" && args[i + 1]) {
        port = parseInt(args[++i], 10);
    }
    else if (args[i] === "--cache-dir" && args[i + 1]) {
        cacheDir = args[++i];
    }
    else if (args[i] === "--config" && args[i + 1]) {
        configPath = args[++i];
    }
    else if (args[i] === "--csp-connect-src" && args[i + 1]) {
        extraConnectSrc.push(args[++i]);
    }
    else if (args[i] === "--output-schema") {
        outputSchema = true;
    }
    else if (!args[i].startsWith("--")) {
        directory = args[i];
    }
}
if (outputSchema) {
    // openapi.json lives at <package-root>/openapi.json — two levels above dist/bin/
    const specPath = new URL("../../openapi.json", import.meta.url);
    // Write through the stream and exit in the drain callback so large specs
    // (which exceed typical OS pipe buffers) aren't truncated by process.exit.
    process.stdout.write(readFileSync(specPath), () => process.exit(0));
}
else if (!directory) {
    console.error("Usage: gxwf-web <directory> [--host 127.0.0.1] [--port 8000] [--cache-dir <path>] [--config <path>] [--csp-connect-src <origin>]... [--output-schema]");
    process.exit(1);
}
else if (!existsSync(directory)) {
    console.error(`Directory does not exist: ${directory}`);
    process.exit(1);
}
else {
    main().catch((err) => {
        console.error("Failed to start server:", err);
        process.exit(1);
    });
}
async function main() {
    let sources;
    if (configPath) {
        if (!existsSync(configPath)) {
            console.error(`Config file not found: ${configPath}`);
            process.exit(1);
        }
        const config = await loadWorkflowToolConfig(configPath);
        const toolOpts = toolInfoOptionsFromConfig(config);
        sources = toolOpts.sources;
        // --cache-dir CLI flag takes precedence over config file
        cacheDir ??= toolOpts.cacheDir;
    }
    // Resolve UI dist: GXWF_UI_DIST env var overrides the bundled copy.
    // Bundled copy is copied from gxwf-ui during build → public/;
    // two levels up from dist/bin/ lands at the package root.
    const uiDirFromEnv = process.env.GXWF_UI_DIST;
    if (uiDirFromEnv && !existsSync(uiDirFromEnv)) {
        console.error(`GXWF_UI_DIST points to non-existent path: ${uiDirFromEnv}`);
        process.exit(1);
    }
    const uiDirCandidate = new URL("../../public", import.meta.url).pathname;
    const uiDir = uiDirFromEnv ?? (existsSync(uiDirCandidate) ? uiDirCandidate : undefined);
    const { server, ready } = createApp(directory, {
        cacheDir,
        sources,
        uiDir,
        extraConnectSrc,
    });
    server.listen(port, host, () => {
        console.log(`gxwf-web listening on ${host}:${port}`);
        console.log(`Serving workflows from: ${directory}`);
        if (uiDir) {
            console.log(`UI: http://${host}:${port}/`);
        }
        else {
            console.log("UI: not available (run pnpm build to bundle the frontend)");
        }
        if (configPath)
            console.log(`Config: ${configPath}`);
    });
    void ready.then(() => {
        console.log("Tool cache loaded, workflows discovered.");
    });
}
//# sourceMappingURL=gxwf-web.js.map