#!/usr/bin/env qore
# -*- mode: qore; indent-tabs-mode: nil -*-

# @file qdp command-line interface for the DataProvider module

/*  Copyright 2019 - 2026 Qore Technologies, s.r.o.

    Permission is hereby granted, free of charge, to any person obtaining a
    copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
    DEALINGS IN THE SOFTWARE.
*/

%modern

%requires qore >= 1.0

%requires ConnectionProvider
%requires DatasourceProvider
%requires DbDataProvider
%requires Mapper
%requires Util
%requires Logger
# for webhooks
%requires HttpServer
%requires RestHandler
# to create the data provider index
%requires ProviderIndex
%requires QoreHistory

%try-module yaml
%define NoYaml
%endtry

%requires linenoise

%requires json

%exec-class QdpCmd

class QdpCmd {
    public {
        #! Version string
        const Version = "1.7.0";

        static HttpServer http;

        static string cmd;
        static string app;
        static string action;

        static bool ix;

        #! port for the HTTP server
        static int http_port = 0;

        # Global mutex for webhook handlers
        static Mutex wh_lock();

        # Global map for webhook handlers: webhook -> handler
        static hash<string, WebhookHandler> whm;

        # console logger
        LoggerInterface logger;

        #! Color output helper
        static Util::TerminalColor color;

        #! Signal handler flag for graceful shutdown
        static bool shutdown_requested = False;

        #! program options
        const Opts = {
            "bulk": "b,bulk",
            "createindex": "I,create-index",
            "dryrun": "d,dry-run",
            "host": "H,host=s",
            "json": "J,json",
            "limit": "l,limit=i",
            "listapps": "a,list-apps",
            "listconnections": "c,list-connections",
            "listfactories": "f,list-factories",
            "mapper": "M,mapper=s",
            "listtypes": "t,list-types",
            "modules": "m,module=s@",
            "nocolor": "C,no-color",
            "offset": "O,offset=i",
            "options": "o,options=s",
            "required": "R,show-required",
            "servers": "S,servers",
            "subtype": "s,subtype=s",
            "timeout": "T,timeout=i",
            "verbose": "v,verbose:i+",
            "version": "V,version",
            "exp": "x,expressions",
            "dpql": "q,dpql",
            "dpqlhelp": "Q,dpql-help",
            "pipelinehelp": "P,pipeline-help",
            "yaml": "Y,yaml",
            "help": "h,help",
        };

        #! commands
        const Cmds = {
            "action-info": \QdpCmd::actionInfo(),
            "ai": \QdpCmd::actionInfo(),
            "ainfo": \QdpCmd::actionInfo(),
            "create": \QdpCmd::create(),
            "create-record": \QdpCmd::getCreateRecord(),
            "crecord": \QdpCmd::getCreateRecord(),
            "delete": \QdpCmd::del(),
            "dorequest": \QdpCmd::doRequest(),
            "errors": \QdpCmd::errors(),
            "event": \QdpCmd::event(),
            "example-error": \QdpCmd::exampleError(),
            "example-event": \QdpCmd::exampleEvent(),
            "example-record": \QdpCmd::exampleRecord(),
            "example-request": \QdpCmd::exampleRequest(),
            "example-response": \QdpCmd::exampleResponse(),
            "exerror": \QdpCmd::exampleError(),
            "exevent": \QdpCmd::exampleEvent(),
            "exrecord": \QdpCmd::exampleRecord(),
            "exrequest": \QdpCmd::exampleRequest(),
            "exresponse": \QdpCmd::exampleResponse(),
            "fadd": \QdpCmd::fieldAdd(),
            "fdelete": \QdpCmd::fieldDelete(),
            "field-add": \QdpCmd::fieldAdd(),
            "field-del": \QdpCmd::fieldDelete(),
            "field-update": \QdpCmd::fieldUpdate(),
            "fupdate": \QdpCmd::fieldUpdate(),
            "info": \QdpCmd::getInfo(),
            "interactive": \QdpCmd::interactive(),
            "ix": \QdpCmd::interactive(),
            "ldetails": \QdpCmd::listChildDetails(),
            "levents": \QdpCmd::listEvents(),
            "list": \QdpCmd::listChildren(),
            "list-details": \QdpCmd::listChildDetails(),
            "list-events": \QdpCmd::listEvents(),
            "listen": \QdpCmd::listen(),
            "lmessages": \QdpCmd::listMessages(),
            "lmsgs": \QdpCmd::listMessages(),
            "message": \QdpCmd::message(),
            "msg": \QdpCmd::message(),
            "pcreate": \QdpCmd::providerCreate(),
            "pdelete": \QdpCmd::providerDelete(),
            "pipe": \QdpCmd::pipeline(),
            "pipeline": \QdpCmd::pipeline(),
            "pl": \QdpCmd::pipeline(),
            "provider-create": \QdpCmd::providerCreate(),
            "provider-delete": \QdpCmd::providerDelete(),
            "record": \QdpCmd::getRecord(),
            "reply": \QdpCmd::response(),
            "request": \QdpCmd::request(),
            "response": \QdpCmd::response(),
            "rsearch": \QdpCmd::doRequestSearch(),
            "search": \QdpCmd::search(),
            "send-message": \QdpCmd::sendMessage(),
            "show-providers": \QdpCmd::showProviders(),
            "smessage": \QdpCmd::sendMessage(),
            "smsg": \QdpCmd::sendMessage(),
            "sp": \QdpCmd::showProviders(),
            "update": \QdpCmd::update(),
            "update-record": \QdpCmd::getUpdateRecord(),
            "urecord": \QdpCmd::getUpdateRecord(),
            "upsert": \QdpCmd::upsert(),
        };

        #! Commands that don't need a data provider
        const NoProviderCmds = (
            "action-info": True,
            "ai": True,
            "ainfo": True,
        );

        #! Disambiguation for common commands with the same initial letters
        const DisambiguationMap = {
            "pipe": "supports_read",
            "pipeline": "supports_read",
            "pl": "supports_read",

            "search": "supports_read",
            "send-message": "supports_messages",
            "smessage": "supports_messages",
            "smsg": "supports_messages",

            "record": "has_record",
            "reply": "supports_request",
            "request": "supports_request",
            "response": "supports_request",
            "rsearch": "supports_request",
        };

        #! valid field keys
        const FieldKeys = (
            "type",
            "desc",
            "default_value",
            "opts",
        );
    }

    constructor() {
        # must be called before any data provider operations are performed to allow for automatic configuration from
        # environment variables by supported data provider modules (ex: SalesforceRestDataProvider)
        DataProvider::setAutoConfig();

        GetOpt g(Opts);
        our hash<auto> opts = g.parse3(\ARGV);

        # Initialize color output early (enabled by default if terminal supports it)
        color = new Util::TerminalColor(!opts.nocolor);

        if (opts.help) {
            usage();
        }
        if (opts.dpqlhelp) {
            showDpqlHelp();
        }
        if (opts.pipelinehelp) {
            showPipelineHelp();
        }
        if (opts.version) {
            showVersion();
        }
        if (opts.dpql && opts.exp) {
            error("options --dpql and --expressions are mutually exclusive");
        }

        # Set up signal handlers for graceful shutdown
        set_signal_handler(SIGINT, \QdpCmd::signalHandler());
        set_signal_handler(SIGTERM, \QdpCmd::signalHandler());

        # data provider modules that start background threads or external processes require
        # DataProvider::shutdown() to be called before the process exits
        # NOTE: exit() does not run on_exit blocks; all exit paths must use QdpCmd::exitProgram()
        on_exit {
            DataProvider::shutdown();
        }

        # load any modules
        map load_module($1), opts.modules;

        logger = getLogger();
        DataProvider::setGlobalLogger(logger);
        ProviderIndex::setGlobalLogger(logger);

        if (opts.listconnections) {
            listConnections();
        }
        if (opts.listfactories) {
            listFactories();
        }
        if (opts.listtypes) {
            listTypes();
        }
        if (opts.listapps) {
            listApps();
        }
        if (opts.createindex) {
            createIndex();
        }
        if (!ARGV[0]) {
            usage();
        }

        DataProviderDataContextHelper dch;
        if (opts.options.val()) {
            auto v = parseInputValue(opts.options);
            if (v.typeCode() != NT_HASH) {
                error("options have type %y; expecting \"hash\"", v.fullType());
            }
            dch = new DataProviderDataContextHelper(v);
        }

        logger = getLogger();
        DataProvider::setGlobalLogger(logger);

        if (opts.servers) {
            DataProvider::addOptions(DPO_EnableServers);
        }

        on_error rethrow $1.err, sprintf("%s%s", $1.desc,
            $1.arg instanceof object && $1.arg.hasCallableMethod("getCause")
                ? ": " + $1.arg.getCause().toString()
                : NOTHING);

        AbstractDataProvider provider;
        DataProviderContextHelper pctx;
        try {
            # first extract any data provider options
            string name = shift ARGV;
            # get expression in curly brackets, if any, respecting balanced brackets
            *string dp_opts = (name =~ x/({(?:(?>[^{}]*)|(?0))*})/)[0];
            if (dp_opts) {
                name = replace(name, dp_opts, "");
            } else {
                # remove empty options; the above regex does not catch them :(
                name =~ s/{}//;
            }
            if (name =~ /^@/) {
                splice name, 0, 1;
                # ignore any trailing "/"
                name =~ s/\/+$//;
                list<string> path = name.split("/");
                if (path.size() == 1) {
                    showActions(name);
                }
                app = path[0];
                action = path[1];
                provider = getDataProviderForAppAction(app, action, dp_opts);
            } else {
                list<string> path = name.split("/");
                provider = getDataProvider((shift path) + dp_opts);
                map provider = provider.getChildProviderEx($1), path;
            }
            provider.setLogger(logger);
            # Set debug collector if verbose mode is enabled
            if (opts.verbose) {
                provider.setDebugCollector(new ConsoleDebugInfoCollector(opts.verbose, color));
            }
            pctx = new DataProviderContextHelper(provider);
        } catch (hash<ExceptionInfo> ex) {
            if (!NoProviderCmds{ARGV[0]}) {
                rethrow;
            }
        }

        # Set up fake webhook interface for the TypeScriptActionInterface module if possible
        if (get_module_hash().TypeScriptActionInterface) {
            # make sure symbols are loaded in this Program
            load_module("TypeScriptActionInterface");
            Class cls = Class::forName("TypeScriptActionInterface::TypeScriptActionInterface");
            hash<MethodAccessInfo> info = cls.findStaticMethod("registerWebhookCreateDestroyApis");
            StaticMethodVariant v = info.method.getVariants()[0];
            v.call(\QdpCmd::getWebhook(), \QdpCmd::deleteWebhook());
        }

        on_exit if (http) {
            http.stop();
            delete http;
        }

        cmd = shift ARGV ?? "list";
        *code qdp_action = Cmds{cmd};
        if (!qdp_action) {
            # see if an abbreviation matches
            hash<string, bool> match = map {$1: True}, keys Cmds, $1.equalPartial(cmd);
            # try to disambiguate
            if (provider && (match.size() > 1)) {
                # only consider commands that are applicable for this data provider
                # AbstractDataProvider::getSummaryInfo() is generally faster than getInfo()
                hash<DataProviderSummaryInfo> info = provider.getSummaryInfo();
                match = map {$1: True}, keys match, !exists DisambiguationMap{$1}
                    || (info{DisambiguationMap{$1}} === True)
                    || (info{DisambiguationMap{$1}}.typeCode() == NT_STRING && info{DisambiguationMap{$1}} != "NONE");
            }
            if (match.size() == 1) {
                qdp_action = Cmds{match.firstKey()};
            } else if (match) {
                # check if all matches have the same action
                {
                    foreach string c in (keys match) {
                        if (!qdp_action) {
                            qdp_action = Cmds{c};
                        } else if (Cmds{c} != qdp_action) {
                            break;
                        }
                    }
                }
                if (!qdp_action) {
                    error("unknown action %y; matches %y; please provide additional character(s) to ensure a unique "
                        "match", cmd, keys match);
                }
            } else {
                error("unknown action %y; known actions: %y", cmd, keys Cmds);
            }
        }
        try {
            qdp_action(provider);
        } catch (hash<ExceptionInfo> ex) {
            if (ex.err == "INVALID-OPERATION") {
                error("%s: %s", ex.err, ex.desc);
            } else {
                rethrow;
            }
        }
    }

    hash<auto> getWebhook(hash<auto> h) {
        if (h.method.typeCode() != NT_STRING) {
            throw "WEBHOOK-ERROR", sprintf("\"method\" must be a string when registering a webhook; got type %y (%y)",
                h.method.fullType(), h.method);
        }
        if (!h.callback.callp()) {
            throw "WEBHOOK-ERROR", sprintf("\"callback\" must be a callable value when registering a webhook; got "
                "type %y (%y)", h.callback.fullType(), h.method);
        }
        # auth is validated but ignored
        if (exists h.auth && (h.auth.typeCode() != NT_INT)) {
            throw "WEBHOOK-ERROR", sprintf("\"auth\" must be a valid auth code if present when registering a "
                "webhook; got type %y (%y)", h.auth.fullType(), h.auth);
        }
        # perms is validated but ignored
        if (exists h.perms && h.perms.typeCode() != NT_LIST) {
            throw "WEBHOOK-ERROR", sprintf("\"perms\" must be a list of strings if present when registering a "
                "webhook; got type %y (%y)", h.perms.fullType(), h.perms);
        }

        setupHttpServer();

        string path = get_random_string();

        WebhookHandler handler(h.method, path, h.callback);
        hash<HttpHandlerConfigInfo> hinfo = <HttpHandlerConfigInfo>{
            "path": path,
            "handler": handler,
        };

        AutoLock al(wh_lock);
        http.setDynamicHandler(path, hinfo);
        whm{path} = handler;

        string http_host = opts.host ?? "localhost";
        if (*softint p = (http_host =~ x/:([0-9]+)$/)[0]) {
            http_host =~ s/:.*$//;
            http_port = p;
        }

        return {
            "url": sprintf("http://%s:%d/webhooks/%s", http_host, http_port, path),
        };
    }

    deleteWebhook(hash<auto> info) {
        if (http) {
            string path = (info.url =~ x/\/([^\/]+)$/)[0];
            http.removeDynamicHandler(path, True);
        }
    }

    synchronized setupHttpServer() {
        if (http) {
            return;
        }
        hash<HttpServerOptionInfo> http_opts = <HttpServerOptionInfo>{
            "logger": getLogger("http"),
            "debug": True,
        };

        http = new HttpServer(http_opts);
        http_port = http.addListener(<HttpListenerOptionInfo>{"service": 0}).port;
    }

    private Logger getLogger(string name = "console") {
        LoggerLevel level;
        if (opts.verbose > 1) {
            level = LoggerLevel::getLevelDebug();
        } else if (opts.verbose) {
            level = LoggerLevel::getLevelInfo();
        } else {
            level = LoggerLevel::getLevelError();
        }
        Logger logger(name, level);
        logger.addAppender(new ConsoleAppender());
        return logger;
    }

    #! Static version of getLogger() for use in static command methods
    static Logger getStaticLogger(string name = "pipeline") {
        LoggerLevel level;
        if (opts.verbose > 1) {
            level = LoggerLevel::getLevelDebug();
        } else if (opts.verbose) {
            level = LoggerLevel::getLevelInfo();
        } else {
            level = LoggerLevel::getLevelError();
        }
        Logger logger(name, level);
        logger.addAppender(new ConsoleAppender());
        return logger;
    }

    static exampleRequest(AbstractDataProvider provider) {
        output(provider.getExampleRequestData());
    }

    static exampleResponse(AbstractDataProvider provider) {
        output(provider.getExampleResponseData());
    }

    static exampleRecord(AbstractDataProvider provider) {
        output(provider.getExampleRecordData());
    }

    static listEvents(AbstractDataProvider provider) {
        hash<string, hash<DataProviderMessageInfo>> events = provider.getEventTypes();
        map printf(" - %s\n", $1), keys events;
    }

    static event(AbstractDataProvider provider) {
        *string event = QdpCmd::getString("event");
        *hash<auto> req;
        hash<DataProviderMessageInfo> event_info;
        if (event.val() && event =~ /=/) {
            req = getHashIntern(remove event, "request");
        }
        if (event.val()) {
            req = QdpCmd::getHash("request");
            event_info = provider.getEventInfoWithOptions(event, req);
        }
        if (!event.val()) {
            hash<string, hash<DataProviderMessageInfo>> event_types = provider.getEventTypes();
            if (event_types.size() == 1) {
                event = event_types.firstKey();
                if (req) {
                    event_info = provider.getEventInfoWithOptions(event, req);
                } else {
                    event_info = event_types.firstValue();
                }
            } else {
                QdpCmd::error("Missing required event argument; valid events: %y", keys event_types);
            }
        }
        DataProviderDataContextHelper dch(req);
        QdpCmd::showType(provider, event, event_info);
    }

    static exampleEvent(AbstractDataProvider provider) {
        *string event = QdpCmd::getString("event");
        if (!exists event) {
            *list<string> l = keys provider.getEventTypes();
            if (l.size() == 1) {
                event = l[0];
            } else {
                QdpCmd::error("Missing required event argument; valid events: %y", l);
            }
        }
        output(provider.getExampleEventData(event));
    }

    static errors(AbstractDataProvider provider) {
        *hash<string, AbstractDataProviderType> errs = provider.getErrorResponseTypes();
        *string err = QdpCmd::getString("error");
        if (err) {
            *AbstractDataProviderType type = errs{err};
            if (!type) {
                QdpCmd::error("unknown error code %y; known error codes: %y", err, keys errs);
            }
            QdpCmd::showType(provider, type);
            return;
        }

        if (!opts.verbose) {
            printf("%y\n", keys errs);
        } else {
            map (printf("%s:\n", $1.key), QdpCmd::showType(provider, $1.value, "  ")), errs.pairIterator();
        }
    }

    static exampleError(AbstractDataProvider provider) {
        string error = QdpCmd::getString("error", True);
        output(provider.getExampleErrorResponseData(error));
    }

    static AbstractDataField getField(string name, auto f) {
        if (f.typeCode() != NT_HASH) {
            QdpCmd::error("field %y value must be type \"hash\"; got type %y instead", name, f.type());
        }
        if (*hash<auto> err = (f - FieldKeys)) {
            QdpCmd::error("field %y has unknown keys: %y; known keys: %y", name, keys err, FieldKeys);
        }
        return new QoreDataField(name, f.desc, AbstractDataProviderType::get(f.type ?? "string", f.opts),
            f.default_value);
    }

    static providerCreate(AbstractDataProvider provider) {
        string name = QdpCmd::getString("provider-create 'name'", True);
        hash<auto> desc = QdpCmd::getHash("provider-create description", True);
        *hash<auto> opts = QdpCmd::getHash("provider-create options");

        hash<string, AbstractDataField> fields = map {$1.key: QdpCmd::getField($1.key, $1.value)}, desc.pairIterator();
        provider.createChildProvider(name, fields, opts);
        printf("created provider %s/%s\n", provider.getName(), name);
    }

    static providerDelete(AbstractDataProvider provider) {
        string name = QdpCmd::getString("provider-delete 'name'", True);
        provider.deleteChildProvider(name);
        printf("deleted provider %s/%s\n", provider.getName(), name);
    }

    static fieldAdd(AbstractDataProvider provider) {
        string name = QdpCmd::getString("field-add 'name'", True);
        hash<auto> desc = QdpCmd::getHash("field-add description", True);
        *hash<auto> opts = QdpCmd::getHash("field-add options");
        AbstractDataField field = QdpCmd::getField(name, desc);
        provider.addField(field, opts);
        printf("added field %y to provider %y\n", name, provider.getName());
    }

    static fieldUpdate(AbstractDataProvider provider) {
        string old_name = QdpCmd::getString("field-update 'old name'", True);
        string new_name = QdpCmd::getString("field-update 'new name'", True);
        *hash<auto> desc = QdpCmd::getHash("field-update description", True);
        *hash<auto> opts = QdpCmd::getHash("field-update options");
        AbstractDataField field;
        if (desc) {
            field = QdpCmd::getField(new_name, desc);
        } else {
            *hash<string, AbstractDataField> fields = provider.getRecordType();
            if (!fields{old_name}) {
                QdpCmd::error("provider %y has no field %y to update", provider.getName(), old_name);
            }
            field = fields{old_name};
        }
        provider.updateField(old_name, field, opts);
        if (old_name == new_name) {
            printf("updated field %y in provider %y\n", old_name, provider.getName());
        } else {
            printf("renamed field %y -> %y in provider %y\n", old_name, new_name, provider.getName());
        }
    }

    static fieldDelete(AbstractDataProvider provider) {
        string name = QdpCmd::getString("field-delete 'name'", True);
        provider.deleteField(name);
        printf("deleted field %y from provider %y\n", name, provider.getName());
    }

    static getInfo(AbstractDataProvider provider) {
        hash<DataProviderInfo> info = provider.getInfo();

        # For JSON/YAML output, convert type objects to serializable data
        if (opts.json || opts.yaml) {
            output(provider.getInfoAsData());
            return;
        }

        # User-friendly formatted output
        # Basic info section
        printf("%s\n", color.bold("Provider"));
        printf("  %s: %s\n", color.key("Name"), info.name);
        if (info.display_name && info.display_name != info.name) {
            printf("  %s: %s\n", color.key("Display Name"), info.display_name);
        }
        printf("  %s: %s\n", color.key("Type"), color.type(info.type));
        if (info.short_desc) {
            printf("  %s: %s\n", color.key("Description"), info.short_desc);
        }

        # Constructor options
        if (info.constructor_options) {
            printf("%s\n", color.bold("Constructor Options"));
            foreach hash<auto> opt in (info.constructor_options.pairIterator()) {
                string type_str = (map $1.getName(), opt.value.type).join("|");
                string req = opt.value.required ? color.error(" (required)") : "";
                printf("  %s [%s]%s\n", color.key(opt.key), color.type(type_str), req);
                if (opt.value.short_desc) {
                    printf("    %s\n", opt.value.short_desc);
                }
                if (opt.value.allowed_values) {
                    printf("    %s: %s\n", color.dim("values"),
                        (map $1.value, opt.value.allowed_values).join(", "));
                }
                if (exists opt.value.default_value) {
                    printf("    %s: %y\n", color.dim("default"), opt.value.default_value);
                }
            }
        }

        # Capabilities section
        printf("%s\n", color.bold("Capabilities"));
        list<string> caps = ();
        if (info.supports_read) push caps, "read";
        if (info.supports_create) push caps, "create";
        if (info.supports_update) push caps, "update";
        if (info.supports_upsert) push caps, "upsert";
        if (info.supports_delete) push caps, "delete";
        if (info.supports_native_search) push caps, "search";
        if (info.supports_bulk_read) push caps, "bulk-read";
        if (info.supports_bulk_create) push caps, "bulk-create";
        if (info.supports_bulk_upsert) push caps, "bulk-upsert";
        if (info.supports_request) push caps, "request/response";
        if (info.supports_observable) push caps, "events";
        if (info.supports_messages.val() && info.supports_messages != "NONE") push caps, "messages";

        if (caps) {
            printf("  %s\n", caps.join(", "));
        } else {
            printf("  %s\n", color.dim("(none)"));
        }

        # Record operations
        if (info.has_record) {
            printf("%s\n", color.bold("Record Operations"));
            printf("  %s: %s\n", color.key("Has Record Type"), color.success("Yes"));
            if (info.record_requires_search_options) {
                printf("  %s: %s\n", color.key("Requires Search Options"), "Yes");
            }
            if (info.supports_search_expressions) {
                printf("  %s: %s\n", color.key("Supports Search Expressions"), "Yes");
            }
            if (info.expressions) {
                printf("  %s:\n", color.key("Search Expressions"));
                foreach hash<auto> exp in (info.expressions.pairIterator()) {
                    string label = exp.value.symbol && exp.value.symbol != exp.key
                        ? sprintf("%s (%s)", exp.key, exp.value.symbol)
                        : exp.key;
                string desc = exp.value.short_desc ?? AbstractDataField::getShortDescription(exp.value.desc);
                printf("    - %s%s\n", color.type(label), desc ? ": " + desc : "");
            }
        }
        }

        # Request/Response API
        if (info.supports_request) {
            printf("%s\n", color.bold("Request/Response API"));
            printf("  %s: %s\n", color.key("Supported"), color.success("Yes"));
            *AbstractDataProviderType req_type = provider.getRequestType();
            *AbstractDataProviderType resp_type = provider.getResponseType();
            if (req_type) {
                printf("  %s: %s\n", color.key("Request Type"), req_type.getName());
            }
            if (resp_type) {
                printf("  %s: %s\n", color.key("Response Type"), resp_type.getName());
            }
        }

        # Messages
        *hash<string, hash<DataProviderMessageInfo>> messages;
        if (info.supports_messages.val() && info.supports_messages != "NONE") {
            messages = provider.getMessageTypes();
        }
        if (messages) {
            printf("%s\n", color.bold("Messages"));
            foreach hash<auto> msg in (messages.pairIterator()) {
                string type_info = msg.value.type ? msg.value.type.getName() : "auto";
                printf("  %s %s: %s\n", color.dim("→"), color.key(msg.key), color.type(type_info));
            }
        }

        # Events
        *hash<string, hash<DataProviderMessageInfo>> events;
        if (info.supports_observable) {
            events = provider.getEventTypes();
        }
        if (events) {
            printf("%s\n", color.bold("Events"));
            foreach hash<auto> evt in (events.pairIterator()) {
                string type_info = evt.value.type ? evt.value.type.getName() : "auto";
                printf("  %s %s: %s\n", color.dim("←"), color.key(evt.key), color.type(type_info));
            }
        }

        # Children
        *list<string> child_names = info.children ?? provider.getChildProviderNames();
        if (child_names) {
            printf("%s\n", color.bold("Children"));
            if (child_names.size() <= 10) {
                map printf("  • %s\n", color.key($1)), child_names;
            } else {
                map printf("  • %s\n", color.key($1)), child_names[0..9];
                printf("  %s\n", color.dim(sprintf("... and %d more", child_names.size() - 10)));
            }
        }

        # Provider-specific info (only if verbose)
        if (opts.verbose && info.info) {
            printf("%s\n", color.bold("Additional Info"));
            outputRecord(info.info);
        }

        # no trailing blank line
    }

    static listChildren(AbstractDataProvider provider) {
        *list<string> children = provider.getChildProviderNames();
        if (children) {
            output(children);
        } else {
            printf(provider.getName() + " has no children\n");
        }
    }

    static listChildDetails(AbstractDataProvider provider) {
        *list<hash<DataProviderSummaryInfo>> children = provider.getChildProviderSummaryInfo();
        if (children) {
            if (opts.json || opts.yaml) {
                output(children);
                return;
            }

            code get_code = string sub (hash<auto> h) {
                if (h.has_record) {
                    return "REC";
                }
                if (h.supports_request) {
                    return "API";
                }
                if (h.supports_observable) {
                    return "EVT";
                }
                if (h.supports_messages != MSG_None) {
                    return "MSG";
                }
                if (h.children_can_support_records) {
                    return "REC";
                }
                if (h.children_can_support_apis) {
                    return "API";
                }
                if (h.children_can_support_observers) {
                    return "EVT";
                }
                if (h.children_can_support_messages) {
                    return "MSG";
                }
                return "---";
            };
            map printf("- %s: (%s) %s\n", color.key($1.name), color.type(get_code($1)),
                QdpCmd::getDesc(10, $1, "name")), children;
        } else {
            printf(provider.getName() + " has no children\n");
        }
    }

    static string getDesc(int offset, hash<auto> h) {
        int len = TermIOS::getWindowSize().columns - offset;
        map len -= h{$1}.length(), argv;
        string desc = h.desc ?? "";
        desc =~ s/\n/ /g;
        desc =~ s/ +/ /g;
        if (len < 0) {
            return "";
        }
        if (desc.length() > len) {
            if (len <= 3) {
                splice desc, len;
            } else {
                splice desc, len - 3;
                desc += "...";
            }
        }
        return desc;
    }

    static interactive(AbstractDataProvider provider) {
        provider.checkObservable();
        {
            on_error rethrow $1.err, sprintf("%s (try using \"listen\" instead)", $1.desc);
            provider.checkMessages();
        }
        hash<DataProviderInfo> info = provider.getInfo();
        MyObserver observer(info);
        Observable observable = cast<Observable>(provider);

        ix = True;

        InputHelper input_helper(provider);

        # print welcome message
        if (input_helper.active_msgid) {
            stdout.printf("%s %s; active message: %s\n",
                color.green("listening to events from"),
                color.cyan(provider.getName()),
                color.type(input_helper.active_msgid));
            stdout.printf("type data to send, %s for help, %s to exit\n",
                color.bold("/help"),
                color.dim("Ctrl+C"));
        } else {
            stdout.printf("%s %s\n",
                color.green("listening to events from"),
                color.cyan(provider.getName()));
            stdout.printf("type %s to select a message type, %s for help\n",
                color.bold("/use <msg-id>"),
                color.bold("/help"));
        }

        observable.registerObserver(observer);

        if (observable instanceof DataProvider::DelayedObservable) {
            cast<DataProvider::DelayedObservable>(observable).observersReady();
        }

        while (!shutdown_requested) {
            string input = input_helper.get();
            if (shutdown_requested) {
                break;
            }
            if (input == "exit" || input == "quit") {
                break;
            }

            # Handle /send <id> <data>
            if (input =~ /^\/send(\s|$)/) {
                string rest = trim(input.substr(5));
                (*string send_id, *string send_data) = (rest =~ x/(\S+)\s+(.*)/s);
                if (!send_id) {
                    stdout.printf("%s: usage: /send <msg-id> <data>\n", color.error("ERROR"));
                    continue;
                }
                if (!input_helper.mmap.hasKey(send_id)) {
                    stdout.printf("%s: unknown message type %y; available: %s\n",
                        color.error("ERROR"), send_id,
                        (foldl $1 + ", " + $2, keys input_helper.mmap));
                    continue;
                }
                auto v;
                try {
                    v = parseInputValue(send_data);
                } catch (hash<ExceptionInfo> ex) {
                    stderr.printf("%s: %s; client-side error; the message was not sent\n",
                        ex.err, ex.desc);
                    continue;
                }
                printf("> %s %y -> %y\n", color.info("sending"), send_id, v);
                try {
                    provider.sendMessage(send_id, v);
                } catch (hash<ExceptionInfo> ex) {
                    stderr.printf("%s %s: %s\n", color.error("ERROR:"), ex.err, ex.desc);
                }
                continue;
            }

            # Unrecognized slash command (shouldn't reach here normally)
            if (input[0] == "/") {
                stdout.printf("unknown command %y; type /help for help\n", input);
                continue;
            }

            # Default: send data with active message ID
            *string msgid = input_helper.active_msgid;
            if (!msgid) {
                # Auto-select first available
                msgid = input_helper.setFirstMsgId();
                if (!msgid) {
                    stdout.printf("no message types available\n");
                    continue;
                }
                stdout.printf("auto-selected message type: %s\n", color.type(msgid));
            }

            auto v;
            try {
                v = parseInputValue(input);
            } catch (hash<ExceptionInfo> ex) {
                stderr.printf("%s: %s; client-side error; the message was not sent\n",
                    ex.err, ex.desc);
                continue;
            }
            printf("> %s %y -> %y\n", color.info("sending"), msgid, v);
            try {
                provider.sendMessage(msgid, v);
            } catch (hash<ExceptionInfo> ex) {
                stderr.printf("%s %s: %s\n", color.error("ERROR:"), ex.err, ex.desc);
            }
        }
        ix = False;
        printf("stopped\n");
    }

    static listMessages(AbstractDataProvider provider) {
        hash<string, hash<DataProviderMessageInfo>> messages = provider.getMessageTypes();
        map printf(" - %s\n", $1), keys messages;
    }

    static message(AbstractDataProvider provider) {
        *string message = QdpCmd::getString("message");
        if (!exists message) {
            QdpCmd::error("missing required message argument; valid messages: %y", keys provider.getMessageTypes());
        }
        QdpCmd::showType(provider, message, provider.getMessageInfo(message));
    }

    static listen(AbstractDataProvider provider) {
        provider.checkObservable();
        hash<DataProviderInfo> info = provider.getInfo();
        MyObserver observer(info);
        Observable observable = cast<Observable>(provider);

        observable.registerObserver(observer);

        # Open the event source before announcing that a keystroke will stop it.
        #
        # Opening can take a noticeable amount of time: a subscription may have to connect,
        # authenticate, and negotiate a stream before any event can arrive.  Two things depend on
        # this running here rather than inside the block below:
        #
        # - the "press any key" prompt must not be printed until input is actually being read.
        #   Nothing reads the keyboard until the loop below starts, so a prompt printed first
        #   invites the user to press a key that is only buffered by the terminal and then acted on
        #   whenever the open finally completes - which looks exactly like a hung program that
        #   ignores the keyboard and then exits long after being asked to.
        # - Term (below) clears ISIG, so while it is in scope Ctrl+C is not a signal at all, just a
        #   byte on stdin, and the SIGINT handler installed in main() cannot run.  With the terminal
        #   still in its normal mode here, Ctrl+C during the open is delivered as SIGINT and sets
        #   shutdown_requested, which the loop below honours immediately.
        if (observable instanceof DataProvider::DelayedObservable) {
            stdout.printf("%s %s...\n", color.dim("opening event source"),
                color.cyan(provider.getName()));
            cast<DataProvider::DelayedObservable>(observable).observersReady();
        }

        # a Ctrl+C during the open has already asked for shutdown; do not then invite a keystroke
        if (!shutdown_requested) {
            # print a message
            string timeout_msg = opts.timeout
                ? sprintf(" %s", color.dim(sprintf("(timeout: %ds)", opts.timeout)))
                : "";
            stdout.printf("%s %s%s; press any key or %s to stop listening...\n",
                color.green("listening to events from"),
                color.cyan(provider.getName()),
                timeout_msg,
                color.dim("Ctrl+C"));
        }
        {
            Term t();

            date start = now_us();
            while (observable.isActive() && !shutdown_requested) {
                # Check timeout
                if (opts.timeout && (now_us() - start) > seconds(opts.timeout)) {
                    printf("\n%s listen timed out after %d seconds\n", color.warning("TIMEOUT:"), opts.timeout);
                    break;
                }
                if (stdin.isDataAvailable(250ms)) {
                    stdin.readBinary(1);
                    break;
                }
            }
        }
        bool active = observable.isActive();
        delete provider;
        if (shutdown_requested) {
            printf("listening stopped due to signal\n");
        } else if (active) {
            printf("listening stopped on user request\n");
        } else {
            printf("listening stopped due to an error\n");
        }
    }

    static getRecord(AbstractDataProvider provider) {
        *hash<auto> search_options = QdpCmd::getHash("search options");
        *hash<string, AbstractDataField> rec = provider.getRecordType(search_options);
        if (opts.verbose > 1) {
            printf("%Y\n", (map {$1.key: $1.value.getInfo()}, rec.pairIterator()));
        } else {
            QdpCmd::showRecord(provider, rec);
        }
    }

    static getCreateRecord(AbstractDataProvider provider) {
        *hash<auto> create_options = QdpCmd::getHash("create options");
        *hash<string, AbstractDataField> rec = provider.getCreateRecordType(create_options);
        if (opts.verbose > 1) {
            printf("%Y\n", (map {$1.key: $1.value.getInfo()}, rec.pairIterator()));
        } else {
            QdpCmd::showRecord(provider, rec);
        }
    }

    static getUpdateRecord(AbstractDataProvider provider) {
        *hash<auto> search_options = QdpCmd::getHash("search options");
        *hash<string, AbstractDataField> rec = provider.getUpdateRecordType(search_options);
        if (opts.verbose > 1) {
            printf("%Y\n", (map {$1.key: $1.value.getInfo()}, rec.pairIterator()));
        } else {
            QdpCmd::showRecord(provider, rec);
        }
    }

    static getAllowedValues(reference<string> info, *list<auto> l) {
        if (info) {
            info += " ";
        }
        if (opts.verbose && l[0].typeCode() == NT_HASH) {
            if (l[0].value != l[0].display_name) {
                info += sprintf("allowed_values: %y", (map sprintf("%s (%s)", $1.display_name, $1.value), l));
            } else {
                info += sprintf("allowed_values: %y", (map $1.value, l));
            }
        } else {
            info += sprintf("allowed_values: %y", (map $1.value ?? $1, l));
        }
    }

    static showRecord(*AbstractDataProvider prov, *hash<string, AbstractDataField> rec,
            string offset = "", auto dctxt) {
        hash<string, bool> rmap;
        showRecord(prov, \rmap, rec, offset, dctxt);
    }

    static showRecord(*AbstractDataProvider prov, reference<hash<string, bool>> rmap, *hash<string, AbstractDataField> rec,
            string offset = "", auto dctxt, *bool unsatisfied_deps) {
        foreach hash<auto> i in (rec.pairIterator()) {
            *bool local_unsatisfied_deps = unsatisfied_deps;
            auto dv = i.value.getDefaultValue();
            if (prov && !exists dv && !unsatisfied_deps) {
                if ((*string default_ref_data = i.value.getAttributes().default_ref_data).val()) {
                    dv = prov.getReferenceDataValueSafe(default_ref_data, DataProviderDataContextHelper::getHash());
                } else if (!offset.val() && prov.getSupportedReferenceDataValues(){i.key}) {
                    dv = prov.getReferenceDataValueSafeEx(i.key, DataProviderDataContextHelper::getHash());
                }
            }
            if (opts.required && (!i.value.isMandatory() || exists dv)) {
                continue;
            }
            AbstractDataProviderType type = i.value.getType();
            *hash<auto> attr = i.value.getAttributes();
            # do not request dependent values if dependencies are not satisfied
            if (!local_unsatisfied_deps && attr.depends_on && (dctxt{attr.depends_on}.size() != attr.depends_on.size())) {
                local_unsatisfied_deps = True;
            }
            showField(prov, \rmap, i, dv, type, offset, dctxt, local_unsatisfied_deps);
            *hash<string, AbstractDataField> fields = type.getFields();
            if (fields) {
                string u = type.uniqueHash();
                if (!rmap{u}) {
                    rmap{u} = True;
                    QdpCmd::showRecord(prov, \rmap, fields, offset + "  ", dctxt{i.key}, local_unsatisfied_deps);
                }
            }
        }
    }

    static showField(*AbstractDataProvider prov, reference<hash<string, bool>> rmap, hash<auto> i, auto dv,
            AbstractDataProviderType type, string offset, auto dctxt, *bool unsatisfied_deps) {
        if (opts.verbose) {
            string txt = sprintf("%s%s %s", offset, type.getName(), i.key);
            string info;
            if (*string desc = i.value.getShortDescription()) {
                info = sprintf("desc: %y", QdpCmd::getDesc(0, {"desc": desc}));
            }
            if (exists dv) {
                if (info) {
                    info += " ";
                }
                info += sprintf("default_value: %y", dv);
            }

            if (*list<auto> l = i.value.getAllowedValues()) {
                QdpCmd::getAllowedValues(\info, l);
            } else if (prov && !unsatisfied_deps && (*string ref_data = i.value.getAttributes().ref_data).val()) {
                l = prov.getReferenceDataSafe(ref_data, DataProviderDataContextHelper::getHash());
                QdpCmd::getAllowedValues(\info, l);
            } else if (prov && !unsatisfied_deps && !offset.val() && prov.getSupportedReferenceData(){i.key}
                && (l = prov.getReferenceDataSafeEx(i.key, DataProviderDataContextHelper::getHash()))) {
                QdpCmd::getAllowedValues(\info, l);
            } else if (l = i.value.getElementAllowedValues()) {
                QdpCmd::getAllowedValues(\info, l);
            } else if (prov && !unsatisfied_deps && (ref_data = i.value.getAttributes().element_ref_data).val()) {
                l = prov.getElementReferenceDataSafe(ref_data, DataProviderDataContextHelper::getHash());
                QdpCmd::getAllowedValues(\info, l);
            } else if (prov && !unsatisfied_deps && !offset.val() && prov.getSupportedElementReferenceData(){i.key}
                && (l = prov.getElementReferenceDataSafeEx(i.key, DataProviderDataContextHelper::getHash()))) {
                QdpCmd::getAllowedValues(\info, l);
            }

            if (info) {
                txt += " (" + info + ")";
            }
            print(txt);
        } else {
            string info;
            if (*list<auto> l = i.value.getAllowedValues()) {
                info += sprintf(" (one of: %y)", (map $1.value ?? $1, l));
            } else if (prov && !unsatisfied_deps && (*string ref_data = i.value.getAttributes().ref_data).val()) {
                l = prov.getReferenceDataSafe(ref_data, DataProviderDataContextHelper::getHash());
                if (l) {
                    info += sprintf(" (one of: %y)", (map $1.value ?? $1, l));
                }
            } else if (l = i.value.getElementAllowedValues()) {
                info += sprintf(" (elements: one of: %y)", (map $1.value ?? $1, l));
            } else if (prov && !unsatisfied_deps && (ref_data = i.value.getAttributes().element_ref_data).val()) {
                l = prov.getElementReferenceDataSafe(ref_data, DataProviderDataContextHelper::getHash());
                if (l) {
                    info += sprintf(" (elements: one of: %y)", (map $1.value ?? $1, l));
                }
            }
            printf("%s%s %s%s", offset, type.getName(), i.key, info);
        }
        if (type.getBaseTypeCode() == NT_LIST && (*AbstractDataProviderType element_type = type.getElementType())
            && (*hash<string, AbstractDataField> element_rec = element_type.getFields())) {
            string u = type.uniqueHash();
            if (!rmap{u}) {
                rmap{u} = True;
                print(": elements ->\n");
                QdpCmd::showRecord(prov, \rmap, element_rec, offset + "  ", dctxt{i.key}, unsatisfied_deps);
            } else {
                print(": (type already described)\n");
            }
        } else {
            print("\n");
        }
    }

    static search(AbstractDataProvider provider) {
        *hash<auto> where_cond = QdpCmd::getSearchExpression("search", NOTHING, provider);
        *hash<auto> search_options = QdpCmd::getHash("search options");

        # Add limit/offset to search options if specified
        if (opts.limit) {
            search_options.limit = opts.limit;
        }
        if (opts.offset) {
            search_options.offset = opts.offset;
        }

        AbstractDataProviderRecordIterator i;
        if (opts.bulk) {
            i = provider.searchRecordsBulk(NOTHING, where_cond, search_options).getRecordIterator();
        } else {
            i = provider.searchRecords(where_cond, search_options);
        }

        # Collect results for JSON/YAML output or output directly
        if (opts.json || opts.yaml) {
            list<auto> results = ();
            int count = 0;
            date start = now_us();
            while (i.next()) {
                if (shutdown_requested) {
                    stderr.printf("Search interrupted after %d records\n", count);
                    break;
                }
                if (opts.timeout && (now_us() - start) > seconds(opts.timeout)) {
                    stderr.printf("Search timed out after %d seconds (%d records)\n", opts.timeout, count);
                    break;
                }
                push results, i.getValue();
                ++count;
            }
            output(results);
        } else {
            int count = 0;
            date start = now_us();
            while (i.next()) {
                if (shutdown_requested) {
                    stderr.printf("\nSearch interrupted after %d records\n", count);
                    break;
                }
                if (opts.timeout && (now_us() - start) > seconds(opts.timeout)) {
                    stderr.printf("\nSearch timed out after %d seconds (%d records)\n", opts.timeout, count);
                    break;
                }
                outputRecord(i.getValue());
                ++count;
            }
        }
    }

    static pipeline(AbstractDataProvider provider) {
        # Get output provider spec (required)
        *string output_spec = shift ARGV;
        if (!output_spec) {
            error("pipeline command requires an output provider argument\n"
                "  Usage: qdp <input-provider> pipeline <output-provider> [search-criteria]");
        }

        # Get optional search criteria (reuses existing DPQL/hash/expression patterns)
        *hash<auto> where_cond = QdpCmd::getSearchExpression("pipeline search", NOTHING, provider);
        *hash<auto> search_options = QdpCmd::getHash("search options");

        # Add limit/offset to search options if specified
        if (opts.limit) {
            search_options.limit = opts.limit;
        }
        if (opts.offset) {
            search_options.offset = opts.offset;
        }

        # Resolve output provider
        AbstractDataProvider output_provider;
        try {
            output_provider = resolveProvider(output_spec);
        } catch (hash<ExceptionInfo> ex) {
            error("cannot resolve output provider %y: %s: %s", output_spec, ex.err, ex.desc);
        }

        # Pre-flight validation
        hash<DataProviderSummaryInfo> in_info = provider.getSummaryInfo();
        hash<DataProviderSummaryInfo> out_info = output_provider.getSummaryInfo();
        if (!in_info.supports_read) {
            error("input provider %y does not support reading records", provider.getName());
        }
        if (!out_info.supports_create) {
            error("output provider %y does not support creating records", output_provider.getName());
        }

        # Load optional mapper
        *Mapper mapper = loadMapper();

        # Dry-run: show pipeline plan without executing
        if (opts.dryrun) {
            printf("%s\n", color.bold("Pipeline Plan (dry-run):"));
            printf("  %s %s\n", color.key("Input:"), provider.getName());
            if (mapper) {
                printf("  %s %s (%d field%s)\n", color.key("Mapper:"),
                    is_readable(opts.mapper) ? "file: " + opts.mapper : "inline",
                    mapper.getMapHash().size(),
                    mapper.getMapHash().size() == 1 ? "" : "s");
            } else {
                printf("  %s no (pass-through)\n", color.key("Mapper:"));
            }
            printf("  %s %s\n", color.key("Output:"), output_provider.getName());
            if (where_cond) {
                printf("  %s %y\n", color.key("Filter:"), where_cond);
            }
            if (opts.limit) {
                printf("  %s %d\n", color.key("Limit:"), opts.limit);
            }
            if (opts.offset) {
                printf("  %s %d\n", color.key("Offset:"), opts.offset);
            }
            printf("  %s %s\n", color.key("Bulk:"), opts.bulk ? "yes" : "no");
            printf("  %s %s\n", color.key("Input supports read:"), in_info.supports_read ? "yes" : "no");
            printf("  %s %s\n", color.key("Output supports create:"), out_info.supports_create ? "yes" : "no");
            if (opts.bulk) {
                printf("  %s %s\n", color.key("Output supports bulk create:"),
                    out_info.supports_bulk_create ? "yes" : "no");
            }
            return;
        }

        # Build pipeline with logging + metrics
        Logger plogger = getStaticLogger("pipeline");
        hash<PipelineOptionInfo> pl_opts = <PipelineOptionInfo>{
            "name": sprintf("%s -> %s", provider.getName(), output_provider.getName()),
            "info_log": sub (string fmt) { plogger.info(vsprintf(fmt, argv)); },
            "error_log": sub (string fmt) { plogger.error(vsprintf(fmt, argv)); },
            "debug_log": sub (string fmt) { plogger.debug(vsprintf(fmt, argv)); },
        };

        # Add progress metrics unless JSON/YAML output mode (clean machine-readable output)
        if (!opts.json && !opts.yaml) {
            pl_opts.metrics_collector = new ProgressMetricsCollector();
        }

        DataProviderPipeline pipeline(pl_opts);
        if (mapper) {
            pipeline.append(mapper);
        }
        pipeline.append(new DataProviderOutputProcessor(output_spec, out_info.supports_bulk_create));

        # Handle signal interrupt for graceful shutdown
        code orig_handler = \QdpCmd::signalHandler();
        set_signal_handler(SIGINT, sub (int sig) {
            orig_handler(sig);
            pipeline.abort(True);
        });

        on_exit {
            set_signal_handler(SIGINT, orig_handler);
        }

        # Get search iterator and submit to pipeline
        try {
            if (opts.bulk) {
                AbstractDataProviderBulkRecordInterface bi =
                    provider.searchRecordsBulk(NOTHING, where_cond, search_options);
                pipeline.submit(bi);
            } else {
                AbstractDataProviderRecordIterator i = provider.searchRecords(where_cond, search_options);
                pipeline.submit(i);
            }
            pipeline.waitDone();
        } catch (hash<ExceptionInfo> ex) {
            if (ex.err == "PIPELINE-FAILED") {
                stderr.printf("%s pipeline failed: %s\n", color.error("ERROR:"), ex.desc);
                if (ex.arg) {
                    foreach auto err in (ex.arg) {
                        stderr.printf("  %s %s: %s\n", color.error("-"), err.err, err.desc);
                    }
                }
                QdpCmd::exitProgram(1);
            }
            rethrow;
        }

        # Print final summary
        hash<PipelineInfo> info = pipeline.getInfo();
        if (opts.json || opts.yaml) {
            output(info);
        } else {
            printf("%s %d records in %s (%.1f rec/s)\n",
                color.info("pipeline complete:"),
                info.record_count,
                info.duration.format("HH:mm:SS.xx"),
                info.recs_per_sec);
        }
    }

    static sendMessage(AbstractDataProvider provider) {
        string message_id = QdpCmd::getString("message_id", True);
        auto val = QdpCmd::getAny("data");
        *hash<auto> send_options = QdpCmd::getHash("send options");

        if (provider instanceof DataProvider::DelayedObservable) {
            cast<DataProvider::DelayedObservable>(provider).observersReady();
        }

        provider.sendMessage(message_id, val, send_options);
    }

    static showProviders(AbstractDataProvider provider) {
        QdpCmd::showProviders("/", provider);
    }

    static showProviders(string path, AbstractDataProvider provider) {
        hash<DataProviderInfo> info = provider.getInfo();
        string type;
        if (info.supports_request) {
            type += "A";
        } else {
            type += "-";
        }
        if (info.supports_observable) {
            type += "E";
        } else {
            type += "-";
        }
        if (info.supports_messages != MSG_None) {
            type += "M";
        } else {
            type += "-";
        }
        if (info.has_record && (info.supports_read || info.supports_create || info.supports_update
            || info.supports_upsert)) {
            type += "R";
        } else {
            type += "-";
        }
        if (type != "----") {
            string desc = sprintf("(%s) %s", type, path);
            if (opts.verbose) {
                desc += sprintf(": %s", provider.getShortDesc());
            }
            printf("- %s\n", desc);
        }
        if (path !~ /\/$/) {
            path += "/";
        }
        *list<string> l = QdpCmd::time(sprintf("get provider names: %y", provider.getName()),
            \provider.getChildProviderNames());
        foreach string child in (l) {
            AbstractDataProvider cp = QdpCmd::time(sprintf("get child %y from %y (%s)", child, provider.getName(),
                provider.className()),
                \provider.getChildProviderEx(), child);
            QdpCmd::showProviders(path + child, cp);
        }

        #map QdpCmd::showProviders(path + $1, provider.getChildProviderEx($1)), provider.getChildProviderNames();
    }

    static auto time(string label, code call, ...) {
        date start = now_us();
        auto rv = call_function_args(call, argv);
        date d = now_us() - start;
        if (d > 500ms) {
            printf("CALL %y: %y\n", label, d);
        }
        return rv;
    }

    static actionInfo(*AbstractDataProvider provider) {
        if (!exists app) {
            QdpCmd::error("Missing app and action for action info; use:\n    %s @<app>/<action> %s",
                get_script_name(), cmd);
        }
        hash<DataProviderActionInfo> action = DataProviderActionCatalog::getAppActionEx(app, QdpCmd::action);
        printf("%s/%s (%s%s): %s\n", color.key("@" + app), color.bold(QdpCmd::action),
            color.type(ActionNameMap{action.action_code}),
            (action.action_val.val() ? " \"" + action.action_val + "\"" : ""), action.short_desc);
        action = DataProviderActionCatalog::checkAppActionOptions(action.app, action.action);
        *hash<auto> req = getHashIntern(shift ARGV, "options");
        *hash<string, hash<ActionOptionInfo>> opts = provider
            ? provider.tryGetActionOptionsWithOptions(action, req)
            : action.options;
        if (opts) {
            printf("%s\n", color.bold("Options"));
            foreach hash<auto> i in (opts.pairIterator()) {
                string tn = i.value.type.getName();
                # get allowed values or element allowed values
                string info;
                if (*list<auto> l = i.value.allowed_values) {
                    info += sprintf(", one of: %y", (map $1.value ?? $1, l));
                } else if (provider && (*string ref_data = i.value.ref_data).val()) {
                    l = provider.getReferenceDataSafe(ref_data, DataProviderDataContextHelper::getHash());
                    if (l) {
                        info += sprintf(", one of: %y", (map $1.value ?? $1, l));
                    }
                } else if (l = i.value.element_allowed_values) {
                    info += sprintf(", elements: one of: %y", (map $1.value ?? $1, l));
                } else if (provider && (ref_data = i.value.element_ref_data).val()) {
                    l = provider.getElementReferenceDataSafe(ref_data, DataProviderDataContextHelper::getHash());
                    if (l) {
                        info += sprintf(", elements: one of: %y", (map $1.value ?? $1, l));
                    }
                }
                string req_str = i.value.required ? color.error(" (required)") : "";
                printf("  %s [%s%s]%s: %s\n", color.key(i.key),
                    i.value.required || tn =~ /^\*/ ? "" : "*", color.type(tn), req_str,
                    i.value.short_desc);
                if (info) {
                    printf("    %s%s\n", color.dim("values"), info);
                }
            }
        } else {
            printf("Options: %s\n", color.dim("none"));
        }
        if (action.output_type) {
            printf("%s\n", color.bold("Output"));
            QdpCmd::showType(provider, action.output_type, "  ");
        }
    }

    static update(AbstractDataProvider provider) {
        hash<auto> set = QdpCmd::getHash("update 'set'", True);
        *hash<auto> where_cond = QdpCmd::getSearchExpression("update 'where'", True, provider);

        if (opts.dryrun) {
            printf("%s Would update records matching:\n", color.warning("[DRY-RUN]"));
            printf("  %s: ", color.key("where"));
            outputRecord(where_cond);
            printf("  %s: ", color.key("set"));
            outputRecord(set);
            return;
        }

        int rec_count = provider.updateRecords(set, where_cond);
        printf("%s %d record%s updated\n", color.success("SUCCESS:"), rec_count, rec_count == 1 ? "" : "s");
    }

    static create(AbstractDataProvider provider) {
        *hash<auto> rec = QdpCmd::getHash("create");
        if (!exists rec) {
            QdpCmd::error("missing argument to 'create' action; a hash is required");
        }

        if (opts.dryrun) {
            printf("%s Would create record(s):\n", color.warning("[DRY-RUN]"));
            outputRecord(rec);
            return;
        }

        *hash<auto> rv = provider.createRecordsBulk(rec);
        if (opts.verbose) {
            printf("new record(s): ");
            output((map $1, rv.contextIterator()));
        }
        int size = rv.firstValue().lsize();
        printf("%s %d record%s successfully created\n", color.success("SUCCESS:"), size, size == 1 ? "" : "s");
    }

    static upsert(AbstractDataProvider provider) {
        *hash<auto> rec = QdpCmd::getHash("upsert");
        *hash<auto> upsert_options = QdpCmd::getHash("upsert options");

        if (opts.dryrun) {
            printf("%s Would upsert record(s):\n", color.warning("[DRY-RUN]"));
            outputRecord(rec);
            if (upsert_options) {
                printf("  %s: ", color.key("options"));
                outputRecord(upsert_options);
            }
            return;
        }

        *list<string> result = provider.upsertRecordsBulk(rec, upsert_options);
        printf("%s upsert result: ", color.success("SUCCESS:"));
        output(result);
    }

    static del(AbstractDataProvider provider) {
        *hash<auto> where_cond = QdpCmd::getSearchExpression("delete", NOTHING, provider);

        if (opts.dryrun) {
            printf("%s Would delete records matching:\n", color.warning("[DRY-RUN]"));
            outputRecord(where_cond);
            return;
        }

        int rec_count = provider.deleteRecords(where_cond);
        printf("%s %d record%s deleted\n", color.success("SUCCESS:"), rec_count, rec_count == 1 ? "" : "s");
    }

    static doRequest(AbstractDataProvider provider) {
        *hash<auto> req = QdpCmd::getHash("request");
        *hash<auto> options = QdpCmd::getHash("request-options");

        # Add timeout to options if specified
        if (opts.timeout && !options.timeout) {
            options.timeout = opts.timeout * 1000;  # convert seconds to milliseconds
        }

        auto resp = provider.doRequest(req, options);
        if (!opts.verbose && resp.hasKey("info") && resp.info."response-uri" && exists resp.body) {
            if (opts.json || opts.yaml) {
                output(resp.body);
            } else {
                printf("%s: ", color.info(resp.info."response-uri"));
                outputRecord(resp.body);
            }
        } else {
            output(resp);
        }
    }

    static doRequestSearch(AbstractDataProvider provider) {
        hash<auto> req = QdpCmd::getHash("request", True);
        hash<auto> where_cond = QdpCmd::getSearchExpression("request-search", True, provider);
        *hash<auto> options = QdpCmd::getHash("request-options");

        # Add limit/offset to options if specified
        if (opts.limit) {
            options.limit = opts.limit;
        }
        if (opts.offset) {
            options.offset = opts.offset;
        }
        # Add timeout if specified
        if (opts.timeout && !options.timeout) {
            options.timeout = opts.timeout * 1000;
        }

        AbstractDataProviderRecordIterator i = provider.requestSearchRecords(req, where_cond, options);

        # Collect results for JSON/YAML output or output directly
        if (opts.json || opts.yaml) {
            list<auto> results = ();
            int count = 0;
            date start = now_us();
            while (i.next()) {
                if (shutdown_requested) {
                    stderr.printf("Search interrupted after %d records\n", count);
                    break;
                }
                if (opts.timeout && (now_us() - start) > seconds(opts.timeout)) {
                    stderr.printf("Search timed out after %d seconds (%d records)\n", opts.timeout, count);
                    break;
                }
                push results, i.getValue();
                ++count;
            }
            output(results);
        } else {
            int count = 0;
            date start = now_us();
            while (i.next()) {
                if (shutdown_requested) {
                    stderr.printf("\nSearch interrupted after %d records\n", count);
                    break;
                }
                if (opts.timeout && (now_us() - start) > seconds(opts.timeout)) {
                    stderr.printf("\nSearch timed out after %d seconds (%d records)\n", opts.timeout, count);
                    break;
                }
                outputRecord(i.getValue());
                ++count;
            }
        }
    }

    static request(AbstractDataProvider provider) {
        if (*hash<auto> req = QdpCmd::getHash("request")) {
            DataProviderDataContextHelper dch(req);
            QdpCmd::showType(provider, provider.getRequestTypeWithData(req));
        } else {
            QdpCmd::showType(provider, provider.getRequestType());
        }
        if (opts.verbose) {
            *hash<string, hash<DataProviderOptionInfo>> opts = provider.getRequestOptions();
            if (opts) {
                QdpCmd::showOptionHash(provider, opts);
            }
        }
    }

    static response(AbstractDataProvider provider) {
        if (*hash<auto> req = QdpCmd::getHash("request")) {
            DataProviderDataContextHelper dch(req);
            QdpCmd::showType(provider, provider.getResponseTypeWithData(req));
        } else {
            QdpCmd::showType(provider, provider.getResponseType());
        }
    }

    static showOptionHash(AbstractDataProvider prov, *hash<auto> req, string offset = "") {
        foreach hash<auto> i in (req.pairIterator()) {
            foreach AbstractDataProviderType type in (i.value.type) {
                if (i.value.type.lsize() > 1) {
                    printf("%s[%d]: %s %s\n", offset, $#, type.getName(), i.key);
                } else {
                    printf("%s%s %s\n", offset, type.getName(), i.key);
                }
                *hash<string, AbstractDataField> fields = type.getFields();
                if (fields) {
                    QdpCmd::showRecord(prov, fields, offset + "  ");
                }
            }
        }
    }

    static showType(*AbstractDataProvider prov) {
        # intentionally empty
    }

    static showType(*AbstractDataProvider prov, string msg, hash<DataProviderMessageInfo> info) {
        printf("%y: %s\n", msg, QdpCmd::getDesc(0, info));
        hash<string, bool> rmap;
        # For simple types without fields, show explanation
        if (info.type && !info.type.getFields()) {
            string type_name = info.type.getName();
            string explanation = QdpCmd::getSimpleTypeExplanation(type_name);
            printf("%s%s\n", type_name, explanation ? " (" + explanation + ")" : "");
        } else if (info.type) {
            QdpCmd::showType(prov, \rmap, info.type);
        }
    }

    #! Returns a human-readable explanation for simple type names
    static string getSimpleTypeExplanation(string type_name) {
        # Handle optional types (starting with *)
        bool optional = type_name[0] == "*";
        string base_type = optional ? type_name.substr(1) : type_name;
        string opt_prefix = optional ? "optional " : "";

        switch (base_type) {
            case "auto": return opt_prefix + "any value of any type";
            case "data": return opt_prefix + "string or binary data";
            case "string": return opt_prefix + "text string";
            case "binary": return opt_prefix + "binary data";
            case "int": return opt_prefix + "integer number";
            case "float": return opt_prefix + "floating-point number";
            case "number": return opt_prefix + "arbitrary-precision number";
            case "bool": return opt_prefix + "true or false";
            case "date": return opt_prefix + "date/time value";
            case "hash": return opt_prefix + "key-value mapping";
            case "list": return opt_prefix + "list of values";
            case "nothing": return "no value (null)";
            case "softstring": return opt_prefix + "value converted to string";
            case "softint": return opt_prefix + "value converted to integer";
            case "softbool": return opt_prefix + "value converted to boolean";
            case "softdate": return opt_prefix + "value converted to date";
            case "softfloat": return opt_prefix + "value converted to float";
            case "softnumber": return opt_prefix + "value converted to number";
            case "softlist": return opt_prefix + "value converted to list";
            default: return "";
        }
    }

    static showType(*AbstractDataProvider prov, AbstractDataProviderType type, *string offset) {
        hash<string, bool> rmap;
        QdpCmd::showType(prov, \rmap, type, offset);
    }

    static showType(*AbstractDataProvider prov, reference<hash<string, bool>> rmap, AbstractDataProviderType type,
            *string offset) {
        *hash<string, AbstractDataField> fields = type.getFields();
        # get data context
        auto dctxt = DataProviderDataContextHelper::get();
        if (fields) {
            QdpCmd::showRecord(prov, \rmap, fields, offset, dctxt);
        } else {
            if (type.getBaseTypeCode() == NT_LIST && (*AbstractDataProviderType element_type = type.getElementType())
                && (*hash<string, AbstractDataField> element_rec = element_type.getFields())) {
                printf("%s%s elements ->\n", type.getName(), offset);
                QdpCmd::showRecord(prov, \rmap, element_rec, offset + "  ", dctxt[0]);
            } else {
                printf("%s%s\n", offset, type.getName());
            }
        }

        if (prov) {
            *hash<auto> tags = type.getTags();
            string info;
            if (tags.ref_data.val()) {
                *list<auto> l = prov.getReferenceDataSafe(tags.ref_data, DataProviderDataContextHelper::getHash());
                QdpCmd::getAllowedValues(\info, l);
            } else if (tags.element_ref_data.val()) {
                *list<auto> l = prov.getElementReferenceDataSafe(tags.element_ref_data, DataProviderDataContextHelper::getHash());
                QdpCmd::getAllowedValues(\info, l);
            }
            if (info) {
                printf("  %s%s\n", offset, info);
            }
        }
    }

    static *hash<auto> getSearchExpression(string action, *bool required, *AbstractDataProvider provider) {
        auto arg = shift ARGV;
        if (opts.dpql) {
            if (!exists arg) {
                if (required) {
                    QdpCmd::error("Missing required %s argument; expecting type \"string\"", action);
                }
                return;
            }
            return QdpCmd::parseDpqlExpression(arg, provider, DataProviderDataContextHelper::getHash());
        }

        *hash<auto> rv;
        if (opts.exp) {
            rv = QdpCmd::getHashIntern(arg, action, required);
            if (rv && rv.size() == 2 && rv.exp.typeCode() == NT_STRING && rv.hasKey("args")) {
                return QdpCmd::getExpression(rv.exp, rv.args);
            }
            return rv;
        }

        if (!exists arg) {
            if (required) {
                QdpCmd::error("Missing required %s argument; expecting type \"hash\"", action);
            }
            return;
        }

        if (QdpCmd::isDpqlCandidate(arg)) {
            hash<auto> parsed = QdpCmd::parseDpqlExpressionWithErrors(arg, provider,
                DataProviderDataContextHelper::getHash());
            if (!parsed.errors) {
                return parsed.expression;
            }
            # Legacy fallback is only for qdp auto-detection (no --dpql / --expressions).
            *hash<auto> legacy = QdpCmd::tryGetHashValue(arg);
            if (legacy) {
                return legacy;
            }
            QdpCmd::error(QdpCmd::formatDpqlErrors(parsed.errors, parsed.diagnostics, arg));
        }

        # Try legacy key=value syntax (parse_to_qore_value) before format-dependent parsing,
        # since parseInputValue with -Y/--yaml won't understand key=value syntax.
        {
            *hash<auto> legacy = QdpCmd::tryGetHashValue(arg);
            if (legacy) {
                return legacy;
            }
        }

        return QdpCmd::getHashIntern(arg, action, required);
    }

    static bool isDpqlCandidate(string text) {
        return (text =~ /@/)
            || (text =~ /==|!=|=~|&&|\|\|/)
            || (text =~ /\bbetween\b|\bin\b/);
    }

    static bool isEmptyDpqlExpression(string dpql) {
        string trimmed = trim(dpql);
        return !trimmed || trimmed == "-" || trimmed == "{}";
    }

    static *hash<DataProviderExpression> parseDpqlExpression(string dpql, *AbstractDataProvider provider,
            *hash<auto> action_opts) {
        hash<auto> parsed = QdpCmd::parseDpqlExpressionWithErrors(dpql, provider, action_opts);
        if (parsed.errors) {
            QdpCmd::error(QdpCmd::formatDpqlErrors(parsed.errors, parsed.diagnostics, dpql));
        }
        return parsed.expression;
    }

    static hash<auto> parseDpqlExpressionWithErrors(string dpql, *AbstractDataProvider provider,
            *hash<auto> action_opts) {
        if (QdpCmd::isEmptyDpqlExpression(dpql)) {
            return {
                "expression": NOTHING,
                "diagnostics": (),
                "errors": (),
            };
        }
        *hash<string, hash<DataProviderExpressionInfo>> expressions;
        if (provider) {
            expressions = provider.getExpressionsWithOptions(action_opts);
        }
        hash<DpqlParseResult> result = DataProvider::parseDpqlExpressionWithInfo(dpql, expressions);
        list<hash<DpqlDiagnostic>> diagnostics = result.diagnostics ?? ();
        if (provider) {
            *hash<string, AbstractDataField> fields = provider.getRecordTypeWithOptions(action_opts, NOTHING);
            if (fields) {
                diagnostics += DataProvider::validateDpqlExpression(dpql, fields, expressions);
            }
        }
        diagnostics = QdpCmd::dedupeDpqlDiagnostics(diagnostics);
        list<hash<DpqlDiagnostic>> errors = QdpCmd::getDpqlErrors(diagnostics);
        if (result.success && result.expression && !QdpCmd::hasDpqlFieldReferences(result.expression)) {
            hash<DpqlDiagnostic> diag = <DpqlDiagnostic>{
                "severity": "error",
                "message": "DPQL expression does not reference any server fields; use @field or legacy search syntax",
                "code": "DPQL-E020",
                "line": 1,
                "column": 1,
                "end_line": 1,
                "end_column": 1,
            };
            diagnostics += diag;
            errors += diag;
        }
        errors = QdpCmd::dedupeDpqlDiagnostics(errors);
        return {
            "expression": result.expression,
            "diagnostics": diagnostics,
            "errors": errors,
        };
    }

    static list<hash<DpqlDiagnostic>> getDpqlErrors(list<hash<DpqlDiagnostic>> diagnostics) {
        if (!diagnostics) {
            return ();
        }
        return select diagnostics, $1.severity == "error";
    }

    static list<hash<DpqlDiagnostic>> dedupeDpqlDiagnostics(list<hash<DpqlDiagnostic>> diagnostics) {
        if (!diagnostics) {
            return ();
        }
        hash<string, bool> seen = {};
        list<hash<DpqlDiagnostic>> rv = ();
        foreach hash<DpqlDiagnostic> diag in (diagnostics) {
            string key = sprintf("%s|%s|%d|%d|%s", diag.severity, diag.code, diag.line, diag.column, diag.message);
            if (!seen{key}) {
                seen{key} = True;
                rv += diag;
            }
        }
        return rv;
    }

    static string formatDpqlErrors(list<hash<DpqlDiagnostic>> errors, list<hash<DpqlDiagnostic>> diagnostics,
            string dpql) {
        if (!errors && diagnostics) {
            errors = diagnostics;
        }
        if (!errors) {
            return "DPQL parse error";
        }
        string msg = sprintf("DPQL parse error: %s", QdpCmd::sanitizeDpqlErrorMessage(errors[0].message, dpql));
        if (errors.size() > 1) {
            list<string> details = ();
            foreach hash<DpqlDiagnostic> diag in (errors) {
                details += sprintf("  - %s (line %d, column %d)",
                    QdpCmd::sanitizeDpqlErrorMessage(diag.message, dpql), diag.line, diag.column);
            }
            msg += "\n" + details.join("\n");
        } else if (errors[0].line) {
            msg += sprintf(" (line %d, column %d)", errors[0].line, errors[0].column);
        }
        return msg;
    }

    static bool hasDpqlFieldReferences(hash<DataProviderExpression> exp) {
        if (!exp) {
            return False;
        }
        if (exp.hasKey("field")) {
            return True;
        }
        if (!exp.args) {
            return False;
        }
        foreach auto arg in (exp.args) {
            if (arg.typeCode() == NT_HASH) {
                if (arg.hasKey("field")) {
                    return True;
                }
                if (arg.hasKey("exp") && QdpCmd::hasDpqlFieldReferences(arg)) {
                    return True;
                }
            }
        }
        return False;
    }

    static string sanitizeDpqlErrorMessage(string message, string dpql) {
        if (message =~ /^Internal parser error:/) {
            string hint;
            if (QdpCmd::isEmptyDpqlExpression(dpql)) {
                hint = " (use '-' or '{}' for an empty expression)";
            }
            return "invalid DPQL expression" + hint;
        }
        return message;
    }

    static hash<DataProviderExpression> getExpression(string exp, auto args) {
        return <DataProviderExpression>{
            "exp": exp,
            "args": QdpCmd::getExpressionArgs(args),
        };
    }

    static *softlist<auto> getExpressionArgs(auto args) {
        if (!exists args) {
            return;
        }
        list<auto> rv = ();
        foreach auto arg in (args) {
            if (arg.size() == 2 && arg.exp.typeCode() == NT_STRING && arg.hasKey("args")) {
                rv += QdpCmd::getExpression(arg.exp, arg.args);
            } else if (arg.field.typeCode() == NT_STRING) {
                rv += cast<hash<DataProviderFieldReference>>(arg);
            } else {
                push rv, arg;
            }
        }
        return rv;
    }

    static *hash<auto> getHash(string action, *bool required) {
        auto arg = shift ARGV;
        return getHashIntern(arg, action, required);
    }

    static *hash<auto> tryGetHashValue(string text) {
        if (!exists text) {
            return;
        }
        try {
            # Always use parse_to_qore_value for legacy key=value parsing,
            # regardless of the -Y/--yaml or --json output format flags.
            auto val = parse_to_qore_value(text);
            if (exists val && val.typeCode() == NT_HASH) {
                return val;
            }
        } catch (hash<ExceptionInfo> ex) {
            # no-op: only used for fallback detection
        }
        return;
    }

    static *hash<auto> getHashIntern(auto arg, string action, *bool required) {
        if (exists arg) {
            arg = parseInputValue(arg);
            if (exists arg && arg.typeCode() != NT_HASH) {
                QdpCmd::error("Invalid %s argument %y; expecting type \"hash\"; got type %y instead", action, arg,
                    arg.type());
            }
        }
        if (required && !exists arg) {
            QdpCmd::error("Missing required %s argument; expecting type \"hash\"", action);
        }
        return arg;
    }

    static *string getString(string action, *bool required) {
        auto arg = shift ARGV;
        if (exists arg) {
            return arg;
        }
        if (required && !arg) {
            QdpCmd::error("Missing required %s argument; expecting type \"string\"", action);
        }
    }

    static auto getAny(string action) {
        auto arg = shift ARGV;
        if (exists arg) {
            arg = parseInputValue(arg);
        }
        return arg;
    }

    private showActions(string app) {
        if (!ENV.QORE_PROVIDER_INDEX_DIR) {
            DataProvider::registerKnownFactories();
        }
        *hash<string, hash<DataProviderActionInfo>> actions = DataProviderActionCatalog::getActionHash(app);
        if (!actions) {
            error("Application %y is unknown; known applications: %y", app, (map $1.name,
                DataProviderActionCatalog::getAllApps()));
        }
        printf("Application %y:\n", app);
        printf("- actions: %y\n", keys actions);
        if (opts.verbose) {
            hash<DataProviderAppInfo> info = DataProviderActionCatalog::getAppEx(app);
            if (info.scheme) {
                hash<ConnectionSchemeInfo> sinfo = ConnectionSchemeCache::getSchemeEx(info.scheme);
                printf("- schemes: %y\n", keys sinfo.schemes);
                *hash<auto> opts = map {$1.key: $1.value.default_value}, sinfo.options.pairIterator(),
                    exists $1.value.default_value;
                if (opts) {
                    printf("- connection options:\n");
                    map printf("  - %s: %y\n", $1.key, $1.value), opts.pairIterator();
                }
            }
        }
        QdpCmd::exitProgram(0);
    }

    private AbstractDataProvider getDataProviderForAppAction(string app_name, string action_name, *string opts) {
        if (!ENV.QORE_PROVIDER_INDEX_DIR) {
            DataProvider::registerKnownFactories();
        }
        *hash<string, hash<DataProviderActionInfo>> actions = DataProviderActionCatalog::getActionHash(app_name);
        if (!actions) {
            error("Application %y is unknown", app_name);
        }
        *hash<DataProviderActionInfo> action = actions{action_name};
        if (!action) {
            error("Application %y does not provide action %y; available actions: %y", app_name, action_name,
                keys actions);
        }
        *hash<auto> options;
        if (opts) {
            options = parseInputValue(opts);
            if (exists options && options.typeCode() != NT_HASH) {
                throw "ACTION-ERROR", sprintf("option string for @%s/%s does not parse to type \"hash\"; got "
                    "type %y instead", app_name, action_name, options.type());
            }
        }
        hash<DataProviderAppInfo> app = DataProviderActionCatalog::getAppEx(app_name);

        string connection;
        AbstractConnection conn;
        if (app.scheme.val()) {
            connection = OptionHelper::getString(options, "connection", True);
            remove options.connection;
            conn = get_connection(connection);
            hash<ConnectionSchemeInfo> scheme_info = ConnectionSchemeCache::getSchemeEx(app.scheme);
            if (!scheme_info.schemes{string scheme = conn.getType()}) {
                throw "APP-CONFIG-ERROR", sprintf("app %y action %y: connection %y has scheme %y; expecting %y", app.name,
                    action.action, connection, scheme, keys scheme_info.schemes);
            }
            if (!conn.hasDataProvider()) {
                throw "APP-CONFIG-ERROR", sprintf("connection %y has no data provider but should be valid for "
                    "app %y action %y", connection, app.name, action.action);
            }
        }

        # check data provider path options
        foreach hash<auto> i in (action.path_vars.pairIterator()) {
            if (!options{i.key}.val()) {
                throw "ACTION-ARG-ERROR", sprintf("app %y action %y: required option %y is missing in \"options\"",
                    app.name, action.action, i.key);
            }
        }

        AbstractDataProvider prov;
        try {
            # NOTE: action.subtype may be NOTHING
            if (conn) {
                prov = conn.getDataProvider(action.subtype);
            } else if (action.cls) {
                prov = DataProviderActionCatalog::getDataProviderForAction(action, \options);
            }
            # set logger on data provider
            prov.setLogger(logger);

            DataProviderDataContextHelper dch(options);
            foreach string seg in (action.path[1..].split("/")) {
                if (!seg.val()) {
                    continue;
                }
                if (*string var = (seg =~ x/^\{([^\}]+)\}$/)[0]) {
                    seg = remove options{var};
                }
                prov = prov.getChildProviderEx(seg);
            }
        } catch (hash<ExceptionInfo> ex) {
            rethrow "ACTION-ERROR", sprintf("error acquiring data provider for app %y action: %y: %s: %s", app.name,
                action.action, ex.err, ex.desc);
        }
        return prov;
    }

    private AbstractDataProvider getDataProvider(string name) {
        if (name =~ /{([^}]*)}/) {
            try {
                AbstractDataProvider dp = DataProvider::getFactoryObjectFromStringUseEnv(name);
                # set logger on data provider
                dp.setLogger(logger);
                return dp;
            } catch (hash<ExceptionInfo> ex) {
                if (ex.err == "FACTORY-ERROR") {
                    error("%s", ex.desc);
                }
                rethrow;
            }
        }

        # load providers from environment and try to load a connection
        try {
            *AbstractDataProvider dp = DataProvider::tryLoadProviderForConnectionFromEnv(name, opts.subtype,
                logger);
            if (dp) {
                # set logger on data provider
                dp.setLogger(logger);
                return dp;
            }
        } catch (hash<ExceptionInfo> ex) {
            if (ex.err == "DATA-PROVIDER-ERROR") {
                error("connection %y exists but does not support the data provider API", name);
            }
            rethrow;
        }

        error("no connection or datasource connection %y exists in any known data provider", name);
    }

    #! Resolve a data provider from a CLI spec string (factory or connection)
    static AbstractDataProvider resolveProvider(string spec) {
        # Extract factory options in balanced braces (same regex as constructor line 292)
        *string dp_opts = (spec =~ x/({(?:(?>[^{}]*)|(?0))*})/)[0];
        string name = spec;
        if (dp_opts) {
            name = replace(name, dp_opts, "");
        } else {
            name =~ s/{}//;
        }

        list<string> path = name.split("/");
        string root = shift path;

        AbstractDataProvider provider;
        string full_root = root + (dp_opts ?? "");

        if (full_root =~ /\{/) {
            # Factory resolution
            provider = DataProvider::getFactoryObjectFromStringUseEnv(full_root);
        } else {
            # Connection resolution
            Logger plogger = getStaticLogger("resolve");
            *AbstractDataProvider dp = DataProvider::tryLoadProviderForConnectionFromEnv(
                root, opts.subtype, plogger);
            if (!dp) {
                error("cannot resolve provider from %y; no matching connection or factory found", spec);
            }
            provider = dp;
        }

        # Navigate child path segments
        map provider = provider.getChildProviderEx($1), path;
        return provider;
    }

    #! Load a Mapper from the -M/--mapper option value (inline hash or file path)
    /** @return a Mapper object, or NOTHING if -M was not specified
    */
    static *Mapper loadMapper() {
        if (!opts.mapper) {
            return;
        }
        string spec = opts.mapper;
        hash<auto> mapv;

        if (is_readable(spec)) {
            string content = ReadOnlyFile::readTextFile(spec);
            if (spec =~ /\.ya?ml$/i) {
%ifndef NoYaml
                mapv = parse_yaml(content);
%else
                error("YAML mapper file requested but yaml module is not available");
%endif
            } else if (spec =~ /\.json$/i) {
                mapv = parse_json(content);
            } else {
                mapv = parse_to_qore_value(content);
            }
        } else {
            mapv = parseInputValue(spec);
        }

        if (mapv.typeCode() != NT_HASH) {
            error("mapper spec must be a hash; got type %y", mapv.fullType());
        }
        return new Mapper(mapv);
    }

    static createIndex() {
        *hash<auto> index = QdpCmd::getHash("index");
        try {
            hash<auto> info = ProviderIndex::createDataProviderIndex(
                index ? cast<hash<DataProviderIndexInfo>>(index) : NOTHING
            );
            printf("Created index %y: %d bytes in %y (%y)\n", info.path, info.size, info.delta, info.summary);
            # apps and actions that could not be initialized are recorded in the index as unavailable
            if (info.summary.failed_apps || info.summary.failed_actions) {
                list<hash<auto>> failures = info.summary.qualification.unavailable;
                printf("%d app(s) and %d action(s) could not be initialized and are unavailable in the index:\n",
                    info.summary.failed_apps, info.summary.failed_actions);
                map printf(" - %s%s: %s: %s\n", $1.app, $1.action ? "/" + $1.action : "", $1.error,
                    $1.description), failures[0..19];
                if (failures.size() > 20) {
                    printf(" - and %d more\n", failures.size() - 20);
                }
            }
            QdpCmd::exitProgram(0);
        } catch (hash<ExceptionInfo> ex) {
            error("%s: %s", ex.err, ex.desc);
        }
    }

    static listApps() {
        DataProvider::registerKnownFactories();
        *list<hash<DataProviderAppInfo>> l = DataProviderActionCatalog::getAllApps();

        if (opts.json || opts.yaml) {
            list<hash<auto>> result = ();
            foreach hash<DataProviderAppInfo> app in (l) {
                *list<hash<DataProviderActionInfo>> actions = DataProviderActionCatalog::getActions(app.name);
                push result, app + {"actions": actions};
            }
            output(result);
            QdpCmd::exitProgram(0);
        }

        foreach hash<DataProviderAppInfo> app in (l) {
            # get actions for app
            *list<hash<DataProviderActionInfo>> actions = DataProviderActionCatalog::getActions(app.name);
            printf("%s: scheme %y, %d action%s: %s\n", color.bold(app.name), app.scheme, actions.size(),
                actions.size() == 1 ? "" : "s", app.desc);
            if (opts.verbose) {
                map printf(" + %s (%s %y): %s\n", color.key($1.action), ActionNameMap{$1.action_code}, $1.path,
                    $1.short_desc), actions;
            }
        }
        QdpCmd::exitProgram(0);
    }

    static listConnections() {
        # get connections
        *hash<string, string> h = map {$1.key: $1.value.url}, get_connection_hash(True).pairIterator();
        # add datasource connections
        h += get_ds_hash(True);

        if (opts.json || opts.yaml) {
            output(h);
            QdpCmd::exitProgram(0);
        }

        if (!h) {
            printf("no connections are present\n");
        } else {
            if (opts.verbose) {
                map printf("%s: %s\n", color.key($1.key), color.value($1.value)), h.pairIterator();
            } else {
                map printf("%s\n", color.key($1)), keys h;
            }
        }
        QdpCmd::exitProgram(0);
    }

    static listFactories() {
        # load known data provider factories
        DataProvider::registerKnownFactories();
        # load providers from environment
        DataProvider::loadProvidersFromEnvironment();
        *list<string> flist = DataProvider::listFactories();

        if (opts.json || opts.yaml) {
            if (opts.verbose) {
                hash<auto> result = map {$1: DataProvider::getFactory($1).getInfoAsData()}, flist;
                output(result);
            } else {
                output(flist);
            }
            QdpCmd::exitProgram(0);
        }

        if (opts.verbose) {
            foreach string f in (flist) {
                printf("%s: ", color.bold(f));
                output(DataProvider::getFactory(f).getInfoAsData());
            }
        } else {
            output(flist);
        }
        QdpCmd::exitProgram(0);
    }

    static listTypes() {
        # load known data provider factories
        DataProvider::registerKnownTypes();
        # load types from environment
        DataProvider::loadTypesFromEnvironment();
        *list<string> tlist = DataProvider::listTypes();

        if (opts.json || opts.yaml) {
            if (opts.verbose) {
                hash<auto> result = map {$1: DataProvider::getType($1).getInfo()}, tlist;
                output(result);
            } else {
                output(tlist);
            }
            QdpCmd::exitProgram(0);
        }

        if (opts.verbose) {
            foreach string t in (tlist) {
                printf("%s: ", color.bold(t));
                output(DataProvider::getType(t).getInfo());
            }
        } else {
            output(tlist);
        }
        QdpCmd::exitProgram(0);
    }

    private static printHelpLine(string colored, string desc, int width) {
        printf("  %s %s\n", TerminalColor::padRight(colored, width), desc);
    }

    static usage() {
        string script = get_script_name();
        int key_width = 24;

        printf("%s - Qore Data Provider CLI Tool\n\n", color.bold(script));

        printf("%s\n", color.bold("USAGE"));
        printf("  %s [options] <provider> [command] [args...]\n\n", script);

        printf("%s\n", color.bold("PROVIDER FORMATS"));
        printHelpLine(color.key("<connection>"), "Use a named connection", key_width);
        printHelpLine(color.key("<factory>{options}"), "Use a factory with options", key_width);
        printHelpLine(color.key("@<app>/<action>"), "Use an app action", key_width);
        printHelpLine(color.key("<provider>/child/..."), "Navigate to child providers", key_width);
        printf("\n");

        printf("%s\n", color.bold("DISCOVERY COMMANDS"));
        printHelpLine(color.key("list") + ", " + color.key("l"),
            "List child providers (default)", key_width);
        printHelpLine(color.key("list-details") + ", " + color.key("ldetails"),
            "List children with details", key_width);
        printHelpLine(color.key("info"), "Show provider information", key_width);
        printHelpLine(color.key("record") + ", " + color.key("rec"),
            "Show record type schema", key_width);
        printHelpLine(color.key("request"), "Show request type (API providers)", key_width);
        printHelpLine(color.key("response") + ", " + color.key("reply"),
            "Show response type (API providers)", key_width);
        printHelpLine(color.key("errors [code]"), "List error response types", key_width);
        printHelpLine(color.key("show-providers") + ", " + color.key("sp"),
            "Show data provider tree", key_width);
        printf("\n");

        printf("%s\n", color.bold("RECORD OPERATIONS"));
        printHelpLine(color.key("search <criteria>"), "Search for records", key_width);
        printHelpLine(color.key("pipeline <output> [search]"), "Pipeline records to output provider", key_width);
        printHelpLine(color.key("create <record>"), "Create new record(s)", key_width);
        printHelpLine(color.key("update <set> <where>"), "Update matching records", key_width);
        printHelpLine(color.key("upsert <record>"), "Create or update record", key_width);
        printHelpLine(color.key("delete <criteria>"), "Delete matching records", key_width);
        printf("\n");

        printf("%s\n", color.bold("API OPERATIONS"));
        printHelpLine(color.key("dorequest <request>"), "Execute API request", key_width);
        printHelpLine(color.key("rsearch <req> <search>"), "Request then search results", key_width);
        printHelpLine(color.key("action-info") + ", " + color.key("ai") + " <info>",
            "Show app action details", key_width);
        printf("\n");

        printf("%s\n", color.bold("EVENT/MESSAGE OPERATIONS"));
        printHelpLine(color.key("listen"), "Listen to events (read-only)", key_width);
        printHelpLine(color.key("interactive") + ", " + color.key("ix"),
            "Interactive mode (send/receive)", key_width);
        printHelpLine(color.key("list-events") + ", " + color.key("levents"),
            "List event types", key_width);
        printHelpLine(color.key("list-messages") + ", " + color.key("lmsgs"),
            "List message types", key_width);
        printHelpLine(color.key("event <name>"), "Show event type details", key_width);
        printHelpLine(color.key("message <name>"), "Show message type details", key_width);
        printHelpLine(color.key("send-message <id> [data]"), "Send a message", key_width);
        printf("\n");

        printf("%s\n", color.bold("EXAMPLES"));
        printHelpLine(color.key("example-request"), "Show example request data", key_width);
        printHelpLine(color.key("example-response"), "Show example response data", key_width);
        printHelpLine(color.key("example-record"), "Show example record data", key_width);
        printHelpLine(color.key("example-event [name]"), "Show example event data", key_width);
        printHelpLine(color.key("example-error [code]"), "Show example error response", key_width);
        printf("\n");

        printf("%s\n", color.bold("SCHEMA MANAGEMENT"));
        printHelpLine(color.key("field-add <name> <desc>"), "Add a field to the schema", key_width);
        printHelpLine(color.key("field-delete <name>"), "Delete a field from schema", key_width);
        printHelpLine(color.key("field-update <old> <new>"), "Rename/update a field", key_width);
        printHelpLine(color.key("provider-create <name> <desc>"), "Create child provider", key_width);
        printHelpLine(color.key("provider-delete <name>"), "Delete child provider", key_width);
        printf("\n");

        printf("%s\n", color.bold("I/O FORMAT OPTIONS"));
        printHelpLine(color.key("-J, --json"), "Use JSON for input and output", key_width);
        printHelpLine(color.key("-Y, --yaml"), "Use YAML for input and output", key_width);
        printHelpLine(color.key("-C, --no-color"), "Disable colored output", key_width);
        printHelpLine(color.key("-v, --verbose"), "Increase verbosity (can repeat)", key_width);
        printf("\n");

        printf("%s\n", color.bold("SEARCH OPTIONS"));
        printHelpLine(color.key("-q, --dpql"), "Use DPQL search expressions", key_width);
        printHelpLine(color.key("-x, --expressions"), "Use legacy search expressions", key_width);
        printHelpLine(color.key("-Q, --dpql-help"), "Show DPQL syntax help and examples", key_width);
        printHelpLine(color.key("-l, --limit=N"), "Limit number of results", key_width);
        printHelpLine(color.key("-O, --offset=N"), "Skip first N results", key_width);
        printHelpLine(color.key("-b, --bulk"), "Use bulk API for searches", key_width);
        printHelpLine(color.key("-T, --timeout=N"), "Timeout in seconds", key_width);
        printf("\n");

        printf("%s\n", color.bold("OTHER OPTIONS"));
        printHelpLine(color.key("-d, --dry-run"), "Preview changes without executing", key_width);
        printHelpLine(color.key("-M, --mapper=X"), "Field mapper (inline hash or file path; see -P)", key_width);
        printHelpLine(color.key("-o, --options=X"), "Set data provider options (Qore hash format)", key_width);
        printHelpLine(color.key("-s, --subtype=X"), "Use subtype when creating from connection", key_width);
        printHelpLine(color.key("-H, --host=X"), "Hostname for webhooks", key_width);
        printHelpLine(color.key("-m, --module=X"), "Load additional module(s)", key_width);
        printHelpLine(color.key("-S, --servers"), "Enable background servers", key_width);
        printHelpLine(color.key("-R, --show-required"), "Show only required fields", key_width);
        printf("\n");

        printf("%s\n", color.bold("INFORMATIONAL"));
        printHelpLine(color.key("-c, --list-connections"), "List known connections", key_width);
        printHelpLine(color.key("-f, --list-factories"), "List known factories", key_width);
        printHelpLine(color.key("-t, --list-types"), "List known types", key_width);
        printHelpLine(color.key("-a, --list-apps"), "List applications", key_width);
        printHelpLine(color.key("-I, --create-index"), "Create provider indices", key_width);
        printHelpLine(color.key("-P, --pipeline-help"), "Show pipeline help and examples", key_width);
        printHelpLine(color.key("-V, --version"), "Show version info", key_width);
        printHelpLine(color.key("-h, --help"), "Show this help", key_width);
        printf("\n");

        printf("%s\n", color.bold("EXAMPLES"));
        printf("  %s mydb info                        %s\n",
            script, color.dim("# Show database provider info"));
        printf("  %s mydb/tables/users search '@name == \"John\"'  %s\n",
            script, color.dim("# Search users table with DPQL"));
        printf("  %s mydb/tables/users search -              %s\n",
            script, color.dim("# Search all records (empty expression)"));
        printf("  %s -J mydb/tables/users search -l 10       %s\n",
            script, color.dim("# JSON output, limit 10"));
        printf("  %s rest'{url=http://api.example.com}' list\n", script);
        printf("  %s @salesforce/search-records search '@query == \"SELECT Id FROM Account\"'\n", script);
        printf("  %s mydb/tables/users search '@name == \"John\"'\n", script);
        printf("  %s mydb/tables/users search -q '@name == \"John\"'\n", script);
        printf("\n");
        printf("  %s mydb/tables/users pipeline 'csvwrite{path=users.csv}'  %s\n",
            script, color.dim("# Export to CSV"));
        printf("  %s 'csvread{path=in.csv}' pipeline mydb/tables/users      %s\n",
            script, color.dim("# Import from CSV"));
        printf("  %s mydb/tables/users pipeline 'csvwrite{path=out.csv}' -d %s\n",
            script, color.dim("# Dry-run pipeline"));

        QdpCmd::exitProgram(1);
    }

    static showDpqlHelp() {
        printf("%s\n", color.bold("DPQL (Data Provider Query Language)"));
        printf("  %s\n", color.info("DPQL is a user-friendly server-independent syntax for fast native server-side record-based data provider searches, updates, and delete operations."));
        printf("\n%s\n", color.bold("SYNTAX"));
        printf("  %s %s %s\n", color.key("@field"), color.type("<op>"), color.key("value"));
        printf("  %s\n", color.key("(@field <op> value) && (@field2 <op> value2)"));
        printf("\n%s\n", color.bold("FIELD REFERENCES"));
        printf("  %s\n", color.key("@name"));
        printf("  %s\n", color.key("@user.email"));
        printf("  %s  %s\n", color.key("@\"field with spaces\""), color.dim("(quoted for special chars)"));
        printf("  %s  %s\n", color.key("@\"literal.dot.name\""), color.dim("(literal dots, not nested)"));
        printf("\n%s\n", color.bold("QUOTING FIELD NAMES"));
        printf("  %s\n", color.dim("Quote field names with special characters using double quotes:"));
        printf("  %s  %s\n", color.key("@\"items[0]\""), color.dim("field name contains brackets"));
        printf("  %s  %s\n", color.key("@\"user==admin\""), color.dim("field name contains operators"));
        printf("  %s  %s\n", color.key("@\"123field\""), color.dim("field name starts with digit"));
        printf("\n%s\n", color.bold("ESCAPE SEQUENCES"));
        printf("  %s\n", color.dim("Use backslash to escape special characters in quoted names:"));
        printf("  %s  %s\n", color.key("@\"field\\\"name\""), color.dim("embedded quote"));
        printf("  %s  %s\n", color.key("@\"path\\\\file\""), color.dim("embedded backslash"));
        printf("  %s  %s\n", color.key("\\n \\r \\t"), color.dim("newline, carriage return, tab"));
        printf("\n%s\n", color.bold("FIELD ACCESSORS"));
        printf("  %s  %s\n", color.key("@items[0]"), color.dim("index accessor (0 = first, -1 = last)"));
        printf("  %s  %s\n", color.key("@items[0..2]"), color.dim("slice accessor (inclusive range)"));
        printf("  %s  %s\n", color.key("@record{key}"), color.dim("key accessor (single key)"));
        printf("  %s  %s\n", color.key("@record{a, b}"), color.dim("key accessor (multiple keys)"));
        printf("  %s  %s\n", color.key("@record.field"), color.dim("dot accessor (member access)"));
        printf("  %s  %s\n", color.key("@data[0]{user}.name"), color.dim("chained accessors"));
        printf("\n%s\n", color.bold("OPERATORS"));
        printf("  %s\n", color.type("== != < <= > >= =~ between in"));
        printf("  %s\n", color.dim("Note: available operators depend on the data provider and server capabilities."));
        printf("  %s\n", color.dim("Use \"qdp <provider> info\" to see supported search expressions."));
        printf("\n%s\n", color.bold("LOGICAL"));
        printf("  %s\n", color.type("&& || !"));
        printf("\n%s\n", color.bold("LITERALS"));
        printf("  %s\n", color.key("strings, numbers, true/false, null"));
        printf("  %s\n", color.key("dates: 2026-01-02 or 2026-01-02T15:20:11.123+01:00"));
        printf("  %s\n", color.key("binary: <deadbeef>"));
        printf("  %s\n", color.key("lists: (one, two, 3)"));
        printf("  %s\n", color.key("hashes: {a=1, b=two}"));
        printf("  %s\n", color.key("unquoted identifiers are strings (ex: @domain == omq)"));
        printf("\n%s\n", color.bold("EMPTY EXPRESSION"));
        printf("  %s\n", color.key("Use '-' or '{}' to search without filters"));
        printf("\n%s\n", color.bold("EXAMPLES"));
        printf("  %s\n", color.key("qdp mydb/tables/users search '@name == \"John\"'"));
        printf("  %s\n", color.key("qdp mydb/tables/users search '@age between 18 and 65'"));
        printf("  %s\n", color.key("qdp mydb/tables/users search '@role in (\"admin\", \"editor\")'"));
        printf("  %s\n", color.key("qdp mydb/tables/users search '(@active == true) && (@age >= 21)'"));
        printf("  %s\n", color.key("qdp mydb/tables/users search '@email =~ /example.com$/i'"));
        printf("  %s\n", color.key("qdp mydb/tables/users search '@created < 2026-12-01'"));
        printf("  %s\n", color.key("qdp mydb/tables/users search '@blob == <deadbeef>'"));
        printf("  %s\n", color.key("qdp mydb/tables/users search '@tags == (one, two, three)'"));
        printf("  %s\n", color.key("qdp mydb/tables/users search '@meta == {a=1, b=two}'"));
        printf("\n%s\n", color.bold("ACCESSOR EXAMPLES"));
        printf("  %s\n", color.key("qdp mydb/tables/orders search '@items[0]{product_id} == 123'"));
        printf("  %s\n", color.key("qdp mydb/tables/users search '@address{city} == \"NYC\"'"));
        printf("  %s\n", color.key("qdp mydb/tables/events search '@tags[-1] == \"important\"'"));
        QdpCmd::exitProgram(0);
    }

    static showPipelineHelp() {
        string script = get_script_name();
        printf("%s\n", color.bold("Pipeline Command"));
        printf("  %s\n", color.info("Pipe records from an input data provider to an output data provider."));
        printf("  %s\n", color.info("Uses DataProviderPipeline for threading, bulk support, and metrics."));

        printf("\n%s\n", color.bold("SYNTAX"));
        printf("  %s %s %s %s %s\n",
            script, color.key("<input>"), color.type("pipeline"), color.key("<output>"),
            color.dim("[search] [options]"));
        printf("  %s\n", color.dim("Aliases: pipeline, pipe, pl"));

        printf("\n%s\n", color.bold("ARGUMENTS"));
        printf("  %s  %s\n", color.key("<input>"),
            "Source provider (connection, factory, or path)");
        printf("  %s  %s\n", color.key("<output>"),
            "Destination provider (connection, factory, or path)");
        printf("  %s  %s\n", color.key("[search]"),
            "Optional filter (DPQL, hash, or expression); omit to stream all records");

        printf("\n%s\n", color.bold("PROVIDER FORMATS"));
        printf("  %s  %s\n", color.key("connection/tables/name"),
            color.dim("Named connection with child path"));
        printf("  %s  %s\n", color.key("factory{opt=val,...}"),
            color.dim("Factory with inline options"));
        printf("  %s  %s\n", color.key("csvread{path=file.csv}"),
            color.dim("CSV file reader"));
        printf("  %s  %s\n", color.key("csvwrite{path=file.csv}"),
            color.dim("CSV file writer"));

        printf("\n%s\n", color.bold("OPTIONS"));
        printf("  %s  %s\n", color.key("-d, --dry-run"),
            "Show pipeline plan without executing");
        printf("  %s  %s\n", color.key("-l, --limit=N"),
            "Limit number of records to transfer");
        printf("  %s  %s\n", color.key("-O, --offset=N"),
            "Skip first N records");
        printf("  %s  %s\n", color.key("-b, --bulk"),
            "Use bulk API for reading and writing");
        printf("  %s  %s\n", color.key("-T, --timeout=N"),
            "Timeout in seconds for the search");
        printf("  %s  %s\n", color.key("-v, --verbose"),
            "Show pipeline logging (repeat for debug)");
        printf("  %s  %s\n", color.key("-J, --json"),
            "Output final summary as JSON (suppresses progress)");
        printf("  %s  %s\n", color.key("-Y, --yaml"),
            "Output final summary as YAML (suppresses progress)");
        printf("  %s  %s\n", color.key("-M, --mapper=X"),
            "Field mapper (inline hash or file path)");
        printf("  %s  %s\n", color.key("-q, --dpql"),
            "Force DPQL parsing for search criteria");
        printf("  %s  %s\n", color.key("-x, --expressions"),
            "Use legacy search expressions");

        printf("\n%s\n", color.bold("MAPPER"));
        printf("  %s\n", color.info("Transform records between input and output using a field mapper."));
        printf("  %s\n", color.info("The mapper uses the Mapper module (inherits AbstractDataProcessor)."));

        printf("\n  %s\n", color.bold("Inline mapper (Qore hash syntax):"));
        printf("  %s\n", color.dim("  -M '{output_field = True}'                    # pass-through (same name)"));
        printf("  %s\n", color.dim("  -M '{out_name = \"in_name\"}'                   # rename field"));
        printf("  %s\n", color.dim("  -M '{age = {name = \"in_age\", type = \"int\"}}' # rename + type coercion"));
        printf("  %s\n", color.dim("  -M '{status = {constant = \"active\"}}'         # constant value"));
        printf("  %s\n", color.dim("  -M '{name = {name = \"in_name\", default = \"N/A\"}}'  # default value"));
        printf("  %s\n", color.dim("With -J, use JSON syntax: -M '{\"out\": \"in\"}'"));

        printf("\n  %s\n", color.bold("File mapper:"));
        printf("  %s\n", color.dim("  -M mapper.yaml    # YAML file (.yaml/.yml)"));
        printf("  %s\n", color.dim("  -M mapper.json    # JSON file (.json)"));
        printf("  %s\n", color.dim("  -M mapper.q       # Qore hash literal (any other extension)"));

        printf("\n  %s\n", color.bold("Mapping value types:"));
        printf("  %s  %s\n", color.key("True"),
            "Pass-through: output field = input field with same name");
        printf("  %s  %s\n", color.key("\"field_name\""),
            "Rename: output field = input field with given name");
        printf("  %s  %s\n", color.key("{name = ..., type = ...}"),
            "Rename with type coercion (int, number, string, date, hash, any)");
        printf("  %s  %s\n", color.key("{constant = value}"),
            "Set a constant value for every record");
        printf("  %s  %s\n", color.key("{name = ..., default = ...}"),
            "Map field with a fallback default value");

        printf("\n  %s\n", color.bold("YAML file example (mapper.yaml):"));
        printf("  %s\n", color.dim("  full_name: \"name\""));
        printf("  %s\n", color.dim("  user_age:"));
        printf("  %s\n", color.dim("    name: \"age\""));
        printf("  %s\n", color.dim("    type: \"int\""));
        printf("  %s\n", color.dim("  status:"));
        printf("  %s\n", color.dim("    constant: \"active\""));

        printf("\n%s\n", color.bold("EXAMPLES"));
        printf("  %s  %s\n",
            color.key(sprintf("%s mydb/tables/users pipeline 'csvwrite{path=users.csv}'", script)),
            color.dim("# Export table to CSV"));
        printf("  %s  %s\n",
            color.key(sprintf("%s 'csvread{path=data.csv}' pipeline mydb/tables/users", script)),
            color.dim("# Import CSV to table"));
        printf("  %s  %s\n",
            color.key(sprintf("%s mydb/tables/users pl 'csvwrite{path=out.csv}' '@active == true'", script)),
            color.dim("# Export filtered records"));
        printf("  %s  %s\n",
            color.key(sprintf("%s mydb/tables/users pipeline mydb2/tables/archive -l 1000", script)),
            color.dim("# Copy 1000 records between DBs"));
        printf("  %s  %s\n",
            color.key(sprintf("%s mydb/tables/users pipeline 'csvwrite{path=out.csv}' -b", script)),
            color.dim("# Bulk mode for large exports"));
        printf("  %s  %s\n",
            color.key(sprintf("%s mydb/tables/users pipeline 'csvwrite{path=out.csv}' -d", script)),
            color.dim("# Dry-run: show plan only"));
        printf("  %s  %s\n",
            color.key(sprintf("%s -J mydb/tables/users pipeline 'csvwrite{path=out.csv}'", script)),
            color.dim("# JSON summary output"));
        printf("  %s  %s\n",
            color.key(sprintf("%s 'csvread{path=in.csv}' pl 'csvwrite{path=out.csv}'"
                " -M '{full_name = \"name\", age = {name = \"user_age\", type = \"int\"}}'", script)),
            color.dim("# Inline mapper"));
        printf("  %s  %s\n",
            color.key(sprintf("%s 'csvread{path=in.csv}' pl 'csvwrite{path=out.csv}' -M mapper.yaml", script)),
            color.dim("# File mapper"));
        printf("  %s  %s\n",
            color.key(sprintf("%s 'csvread{path=in.csv}' pl 'csvwrite{path=out.csv}'"
                " -M '{name = True, status = {constant = \"active\"}}'", script)),
            color.dim("# Pass-through + constant"));

        printf("\n%s\n", color.bold("PROGRESS"));
        printf("  %s\n", color.dim("Progress is shown on stderr every 2 seconds (suppressed with -J/-Y)."));
        printf("  %s\n", color.dim("Press Ctrl+C for graceful shutdown — records already submitted will complete."));

        printf("\n%s\n", color.bold("OUTPUT"));
        printf("  %s\n", color.dim("Default: human-readable summary with record count and throughput."));
        printf("  %s\n", color.dim("With -J/-Y: structured pipeline info (name, status, record_count, duration, recs_per_sec)."));
        QdpCmd::exitProgram(0);
    }

    static error(string fmt) {
        stderr.printf("%s: %s %s\n", get_script_name(), color.error("ERROR:"), vsprintf(fmt, argv));
        exitProgram(1);
    }

    #! Terminates the program after shutting down background data provider services
    /** @param rc the return code for the process

        @note This must be used instead of exit(); data provider modules that start background threads or external
        processes (ex: the JavaScript / TypeScript action interface process pool) register shutdown handlers and
        require DataProvider::shutdown() to be called before the process exits, otherwise external processes are
        left orphaned.  Note that exit() does not run \c on_exit blocks, so the shutdown cannot be handled with a
        scope guard alone
    */
    static exitProgram(softint rc = 0) {
        try {
            DataProvider::shutdown();
        } catch (hash<ExceptionInfo> ex) {
            stderr.printf("%s: %s error shutting down data provider services: %s\n", get_script_name(),
                color.error("ERROR:"), get_exception_string(ex));
        }
        exit(rc);
    }

    static showVersion() {
        printf("%s version %s\n", get_script_name(), Version);
        printf("Qore %s\n", Qore::VersionString);
        printf("JSON I/O: supported\n");
%ifndef NoYaml
        printf("YAML I/O: supported\n");
%else
        printf("YAML I/O: not available (yaml module not installed)\n");
%endif
        printf("Line editing: supported (linenoise)\n");
        QdpCmd::exitProgram(0);
    }

    static signalHandler(int sig) {
        shutdown_requested = True;
        # Print message about graceful shutdown
        stderr.printf("\n%s: received signal %d, shutting down gracefully...\n", get_script_name(), sig);
    }

    #! Output data in the requested format (JSON, YAML, or Qore)
    static output(auto data) {
        if (opts.json) {
            printf("%s\n", make_json(data, JGF_ADD_FORMATTING));
        } else if (opts.yaml) {
%ifndef NoYaml
            printf("%s", make_yaml(data, YAML::BlockStyle));
%else
            error("YAML output requested but yaml module is not available");
%endif
        } else {
            printf("%Y\n", data);
        }
    }

    #! Parse input value according to the current format (JSON, YAML, or Qore)
    static auto parseInputValue(string text) {
        if (opts.json) {
            return parse_json(text);
        }
        if (opts.yaml) {
%ifndef NoYaml
            return parse_yaml(text);
%else
            error("YAML input requested but yaml module is not available");
%endif
        }
        return parse_to_qore_value(text);
    }

    #! Output a single record/hash with optional color formatting
    static outputRecord(auto data) {
        if (opts.json || opts.yaml) {
            output(data);
        } else {
            printf("%s\n", color.formatValue(data));
        }
    }
}

#! Wraps an output data provider's createRecord()/createRecordsBulk() as an AbstractDataProcessor
#! The output provider is created lazily on first submit to ensure it runs in the pipeline's worker thread
#! (some providers like CsvWriteDataProvider create thread-locked streams on construction)
class DataProviderOutputProcessor inherits DataProvider::AbstractDataProcessor {
    private {
        #! Spec string for lazy resolution in worker thread
        string output_spec;
        #! Provider resolved lazily on first submit
        *AbstractDataProvider output_provider;
        #! Whether the output provider supports bulk create
        bool supports_bulk;
    }

    constructor(string output_spec, bool supports_bulk) {
        self.output_spec = output_spec;
        self.supports_bulk = supports_bulk;
    }

    private submitImpl(code enqueue, auto _data) {
        # Lazy-resolve on first call (runs in pipeline worker thread)
        if (!output_provider) {
            output_provider = QdpCmd::resolveProvider(output_spec);
        }
        if (_data.typeCode() == NT_HASH) {
            if (_data.firstValue().typeCode() == NT_LIST) {
                output_provider.createRecordsBulk(_data);
            } else {
                output_provider.createRecord(_data);
            }
        }
        enqueue(_data);
    }

    private bool supportsBulkApiImpl() {
        return supports_bulk;
    }
}

#! Reports pipeline progress to stderr
class ProgressMetricsCollector inherits DataProvider::AbstractPipelineMetricsCollector {
    private {
        date start;
    }

    constructor() {
        start = now_us();
    }

    int getIntervalMs() {
        return 2000;
    }

    int getRecordInterval() {
        return 0;
    }

    reportMetrics(hash<PipelineMetricsSnapshot> snapshot) {
        float elapsed = (now_us() - start).durationSecondsFloat();
        stderr.printf("\r%s %d records (%.1f rec/s, %.0fs elapsed)   ",
            QdpCmd::color.info("progress:"), snapshot.total_records_submitted,
            snapshot.throughput_rps, elapsed);
    }

    shutdown() {
        stderr.printf("\n");
    }
}

class Term {
    public {}
    private {
        TermIOS orig;
    }

    constructor() {
        TermIOS t();

        # get current terminal attributes for stdin
        stdin.getTerminalAttributes(t);

        # save a copy
        orig = t.copy();

        # get local flags
        int lflag = t.getLFlag();

        # disable canonical input mode (= turn on "raw" mode)
        lflag &= ~ICANON;

        # turn off echo mode
        lflag &= ~ECHO;

        # do not check for special input characters (INTR, QUIT, and SUSP)
        lflag &= ~ISIG;

        # set the new local flags
        t.setLFlag(lflag);

        # set minimum characters to return on a read
        t.setCC(VMIN, 1);

        # set character input timer in 0.1 second increments (= no timer)
        t.setCC(VTIME, 0);

        # make these terminal attributes active
        stdin.setTerminalAttributes(TCSADRAIN, t);
    }

    destructor() {
        restore();
    }

    restore() {
        # restore terminal attributes
        stdin.setTerminalAttributes(TCSADRAIN, orig);
    }
}

class MyObserver inherits Observer {
    public {}

    private {
        hash<DataProviderInfo> info;
        TermIOS t();
    }

    constructor(hash<DataProviderInfo> info) {
        self.info = info;
        # get current terminal attributes for stdin
        stdin.getTerminalAttributes(t);
    }

    update(string event_id, hash<auto> data_) {
        string msg = sprintf("received event %s:", QdpCmd::color.cyan(event_id));
        if (!data_) {
            msg += " " + QdpCmd::color.dim("no data");
        }
        if (data_) {
            msg += sprintf("\n%s", QdpCmd::color.formatValue(data_));
        }
        log("<", msg);
        if (info.connection_event == event_id) {
            string protocol = data_.http3 ? "HTTP/3" : (data_.http2 ? "HTTP/2" : "HTTP/1.1");
            log("<", "%s (WebSocket over %s)", QdpCmd::color.success("connected to server"),
                QdpCmd::color.info(protocol));
        } else if (info.disconnection_event == event_id) {
            if (info.supports_auto_reconnect) {
                log("<", "%s%s", QdpCmd::color.warning("disconnected from server"),
                    QdpCmd::ix ? "; trying to reconnect..." : "");
            } else {
                log("<", "%s; auto_reconnect not enabled; exiting",
                    QdpCmd::color.error("disconnected from server"));
                # restore original terminal attributes
                stdin.setTerminalAttributes(TCSADRAIN, t);
                QdpCmd::exitProgram(0);
            }
        }
        stdout.sync();
    }

    log(string inout, string fmt, ...) {
        if (QdpCmd::ix) {
            stdout.print("\r");
        }
        string direction_color = inout == "<" ? QdpCmd::color.green(inout) : QdpCmd::color.yellow(inout);
        string timestamp = QdpCmd::color.dim(now_us().format("YYYY-MM-DD HH:mm:SS.xx"));
        fmt = sprintf("%s %s ", direction_color, timestamp) + fmt;
        string msg = vsprintf(fmt, argv);
        msg =~ s/\n/\015\012/g;
        stdout.print(msg + "\n");
        if (QdpCmd::ix) {
            stdout.print("\r");
        }
    }
}

class ConsoleAppender inherits LoggerAppenderWithLayout {
    constructor() : LoggerAppenderWithLayout("console", new LoggerLayoutPattern("%d{YYYY-MM-DD HH:mm:SS.xx} T%t [%p]: %m%n")) {
        open();
    }

    processEventImpl(int type, auto params) {
        switch (type) {
            case EVENT_LOG:
                params =~ s/\n/\r\n/g;
                print(params);
                break;
        }
    }
}

class InputHelper {
    public {
        AbstractDataProvider provider;
        # message map
        hash<string, hash<DataProviderMessageInfo>> mmap;
        # event map
        *hash<string, hash<DataProviderMessageInfo>> emap;

        #! Active message ID for default send
        *string active_msgid;

        #! Current input/output format for interactive mode ("qore", "json", "yaml")
        string input_format = "qore";

        #! Cached schema hint strings per message ID
        hash<string, string> schema_hints;

        #! Shared history manager
        QoreHistory::History qhistory({"max_length": 100, "dedup_mode": QoreHistory::DEDUP_FULL});

        #! Path to history file (NOTHING if HOME is not set)
        *string history_path;
        const HistoryFile = ".qdp-history";

        const Commands = {
            "/event": True,
            "/events": True,
            "/exit": True,
            "/format": True,
            "/help": True,
            "/history": True,
            "/info": True,
            "/msgs": True,
            "/msg": True,
            "/quit": True,
            "/send": True,
            "/use": True,
        };
    }

    string getPrompt() {
        return active_msgid ? active_msgid + "> " : "> ";
    }

    #! Set active_msgid to the first available message ID; returns the ID or NOTHING
    *string setFirstMsgId() {
        if (mmap) {
            active_msgid = mmap.firstKey();
        }
        return active_msgid;
    }

    constructor(AbstractDataProvider provider) {
        self.provider = provider;
        mmap = provider.getMessageTypes();
        emap = provider.getEventTypes();

        # Initialize format from command-line flags
        if (opts.json) {
            input_format = "json";
        } else if (opts.yaml) {
            input_format = "yaml";
        }

        # Auto-select if only one message type
        if (mmap.size() == 1) {
            active_msgid = mmap.firstKey();
        }

        if (exists ENV.HOME) {
            history_path = ENV.HOME + DirSep + HistoryFile;
        } else {
            stderr.printf("WARNING: HOME not set, history will not be saved\n");
        }

        # Load history via QoreHistory (owns persistence and file format)
        if (history_path) {
            try {
                qhistory.load(history_path);
            } catch (hash<ExceptionInfo> ex) {
                stderr.printf("%y: WARNING: cannot load history: %s: %s\n", history_path,
                    ex.err, ex.desc);
            }
        }

        Linenoise::set_callback(\completion());
        Linenoise::set_hints_callback(\hintsForInput());
        Linenoise::set_syntax_callback(\syntaxHighlight());
        Linenoise::set_right_prompt(getRightPrompt());
        Linenoise::set_completion_case_insensitive(True);
        # Delegate history navigation to QoreHistory (single source of truth)
        Linenoise::set_history_provider(new QoreHistory::QoreHistoryProvider(qhistory));
    }

    destructor() {
        if (history_path) {
            try {
                qhistory.save(history_path);
            } catch (hash<ExceptionInfo> ex) {
                stderr.printf("%y: WARNING: cannot save history: %s: %s\n", history_path,
                    ex.err, ex.desc);
            }
        }
    }

    string get() {
        string line;
        while (True) {
            *string line0 = Linenoise::line(getPrompt());
            if (!exists line0) {
                line = "exit";
                break;
            }
            line = line0;

            if (!line.val()) {
                continue;
            }

            # History expansion (!! !n !-n !prefix !$)
            if (line[0] == "!" && line.length() >= 2) {
                *string expanded = qhistory.expand(line);
                if (exists expanded) {
                    printf("! %s\n", expanded);
                    line = expanded;
                }
            }

            # Add to QoreHistory (owns persistence, timestamps, dedup)
            qhistory.add(line);
            # Save eagerly after each command
            if (history_path) {
                try {
                    qhistory.save(history_path);
                } catch (hash<ExceptionInfo> ex) {
                    stderr.printf("%y: WARNING: cannot save history: %s: %s\n", history_path,
                        ex.err, ex.desc);
                }
            }

            # Slash commands
            if (line == "/help" || line == "/?") {
                interactiveHelp();
                continue;
            }
            if (line == "/info") {
                interactiveInfo(provider);
                continue;
            }
            if (line == "/msgs") {
                showAllMessages();
                continue;
            }
            if (line == "/events") {
                showAllEvents();
                continue;
            }
            if (line =~ /^\/msg\s+/) {
                showMessageInfo(provider, trim(line.substr(5)));
                continue;
            }
            if (line =~ /^\/event\s+/) {
                showEventInfo(provider, trim(line.substr(7)));
                continue;
            }
            if (line == "/history" || line =~ /^\/history\s/) {
                handleHistory(line.length() > 8 ? trim(line.substr(8)) : "");
                continue;
            }
            if (line == "/use" || line =~ /^\/use\s/) {
                handleUse(line.size() > 4 ? trim(line.substr(4)) : "");
                continue;
            }
            if (line == "/format" || line =~ /^\/format\s/) {
                handleFormat(line.length() > 7 ? trim(line.substr(7)) : "");
                continue;
            }
            # /send is returned to interactive() for processing
            if (line =~ /^\/send(\s|$)/) {
                break;
            }
            if (line == "/exit" || line == "/quit") {
                line = "exit";
                break;
            }
            # Bare exit/quit for convenience
            if (line == "exit" || line == "quit") {
                break;
            }
            # Unrecognized slash command
            if (line[0] == "/") {
                printf("unknown command %y; type /help for help\n", line);
                continue;
            }

            # Default: return as data to send
            break;
        }

        return line;
    }

    private handleUse(string args) {
        string id = trim(args);
        if (!id.val()) {
            # Show current
            if (active_msgid) {
                printf("active message type: %s\n", QdpCmd::color.type(active_msgid));
            } else {
                printf("no active message type; use /use <id> to set one\n");
            }
            return;
        }
        if (!mmap.hasKey(id)) {
            printf("unknown message type %y; available: %s\n", id,
                (foldl $1 + ", " + $2, (map QdpCmd::color.type($1), keys mmap)));
            return;
        }
        active_msgid = id;
        printf("active message type set to: %s\n", QdpCmd::color.type(id));
    }

    #! Returns the right prompt string, including format indicator if not default
    private string getRightPrompt() {
        if (input_format == "json") {
            return "[JSON] " + provider.getName();
        }
        if (input_format == "yaml") {
            return "[YAML] " + provider.getName();
        }
        return provider.getName();
    }

    private handleFormat(string args) {
        string mode = trim(args);
        if (!mode.val()) {
            printf("current format: %s\n", QdpCmd::color.type(input_format));
            return;
        }
        switch (mode) {
            case "qore":
                input_format = "qore";
                delete opts.json;
                delete opts.yaml;
                break;
            case "json":
                input_format = "json";
                opts.json = True;
                delete opts.yaml;
                break;
            case "yaml":
%ifndef NoYaml
                input_format = "yaml";
                delete opts.json;
                opts.yaml = True;
%else
                printf("%s: YAML format not available (yaml module not installed)\n",
                    QdpCmd::color.error("ERROR"));
                return;
%endif
                break;
            default:
                printf("%s: unknown format %y; use: json, yaml, qore\n",
                    QdpCmd::color.error("ERROR"), mode);
                return;
        }
        Linenoise::set_right_prompt(getRightPrompt());
        printf("format set to: %s\n", QdpCmd::color.type(input_format));
    }

    private handleHistory(string args) {
        if (!args.val()) {
            # Show all history
            int i = 1;
            foreach hash<QoreHistory::HistoryEntry> item in (qhistory.getItems()) {
                printf("  %3d  %s  %s\n", i++,
                    format_date("YYYY-MM-DD HH:mm:SS", item.timestamp), item.text);
            }
            return;
        }

        if (args =~ /^search\s+/) {
            string pattern = trim(args.substr(7));
            if (!pattern.val()) {
                printf("usage: /history search <pattern>\n");
                return;
            }
            list<hash<QoreHistory::HistoryEntry>> matches =
                qhistory.search(pattern, QoreHistory::MATCH_SUBSTRING);
            if (!matches) {
                printf("no history entries matching %y\n", pattern);
                return;
            }
            foreach hash<QoreHistory::HistoryEntry> item in (matches) {
                printf("  %s  %s\n", format_date("YYYY-MM-DD HH:mm:SS", item.timestamp),
                    item.text);
            }
            printf("  %d match%s\n", matches.size(), matches.size() == 1 ? "" : "es");
            return;
        }

        if (args == "clear") {
            int count = qhistory.size();
            qhistory.clear();
            printf("history cleared (%d entr%s removed)\n", count, count == 1 ? "y" : "ies");
            return;
        }

        if (args =~ /^delete\s+/) {
            string nstr = trim(args.substr(7));
            if (nstr !~ /^\d+$/) {
                printf("usage: /history delete <n> (1-based entry number)\n");
                return;
            }
            int n = nstr.toInt();
            if (n < 1) {
                printf("entry number must be >= 1\n");
                return;
            }
            if (qhistory.removeAt(n - 1)) {
                printf("history entry %d deleted\n", n);
            } else {
                printf("invalid entry number %d (history has %d entries)\n", n, qhistory.size());
            }
            return;
        }

        printf("unknown /history subcommand %y; use: search <pat>, clear, delete <n>\n", args);
    }

    private interactiveHelp() {
        printf("%s\n", QdpCmd::color.bold("SENDING MESSAGES"));
        printHelpLine("<data>", "Send data using the active message type");
        printHelpLine("/send <id> <data>", "Send data with a specific message type");
        printHelpLine("/use <id>", "Set the active message type");
        printHelpLine("/use", "Show the current active message type");
        printf("                    Example: action=ping,id=123\n");
        if (mmap) {
            printf("  %s: %s\n", QdpCmd::color.key("Available"),
                (foldl $1 + ", " + $2, (map QdpCmd::color.type($1), keys mmap)));
        }
        printf("%s\n", QdpCmd::color.bold("SESSION COMMANDS"));
        printHelpLine("/help, /?", "Show this help");
        printHelpLine("/info", "Show connection info");
        printHelpLine("/msgs", "List all available messages");
        printHelpLine("/events", "List all available events");
        printHelpLine("/msg <id>", "Show message type details");
        printHelpLine("/event <id>", "Show event type details");
        printHelpLine("/format [mode]", "Set input/output format (json, yaml, qore)");
        printHelpLine("/quit, /exit", "Exit interactive mode");
        printHelpLine("quit, exit", "Exit interactive mode");
        printf("%s\n", QdpCmd::color.bold("HISTORY"));
        printHelpLine("/history", "Show command history");
        printHelpLine("/history search <pat>", "Search history for pattern");
        printHelpLine("/history clear", "Clear command history");
        printHelpLine("/history delete <n>", "Delete history entry by number");
        printHelpLine("!!", "Repeat last command");
        printHelpLine("!<n>", "Repeat command by number");
        printHelpLine("!-<n>", "Repeat command relative to end");
        printHelpLine("!<prefix>", "Repeat last command starting with prefix");
        printHelpLine("!$", "Last word of last command");
        printf("%s\n", QdpCmd::color.bold("KEYBOARD SHORTCUTS"));
        printHelpLine("Enter", "Send message / execute command");
        printHelpLine("Ctrl+C", "Exit interactive mode");
        printHelpLine("Up/Down", "Previous command in history");
        printHelpLine("Ctrl+R/Ctrl+S", "Search history backward/forward");
        printHelpLine("Tab", "Autocomplete");
    }

    private printHelpLine(string key, string desc) {
        int padding = 20 - key.length();
        if (padding < 2) {
            padding = 2;
        }
        printf("  %s%s%s\n", QdpCmd::color.key(key), strmul(" ", padding), desc);
    }

    private interactiveInfo(AbstractDataProvider provider) {
        printf("%s\n", QdpCmd::color.bold("Connection Info"));
        printf("  %s: %s\n", QdpCmd::color.key("Provider"), provider.getName());
        printf("  %s: %s\n", QdpCmd::color.key("Description"), provider.getShortDesc());

        # Connection details
        *hash<DataProviderConnectionInfo> cinfo = provider.getConnectionInfo();
        if (cinfo) {
            if (cinfo.url) {
                printf("  %s: %s\n", QdpCmd::color.key("URL"), cinfo.url);
                printf("  %s: %s\n", QdpCmd::color.key("Connected"),
                    cinfo.connected ? QdpCmd::color.success("Yes") : QdpCmd::color.error("No"));
                printf("  %s: %s\n", QdpCmd::color.key("Auto Reconnect"),
                    cinfo.auto_reconnect ? "Yes" : "No");
            }
            if (cinfo.info) {
                formatConnectionInfo(cinfo.info);
            }
        }

        # Messages summary
        *hash<string, hash<DataProviderMessageInfo>> messages = provider.getMessageTypes();
        if (messages) {
            printf("  %s: %s (type '%s <id>' for details)\n", QdpCmd::color.key("Outgoing Messages"),
                (foldl $1 + ", " + $2, keys messages), QdpCmd::color.key("/msg"));
        }

        # Events summary
        *hash<string, hash<DataProviderMessageInfo>> events = provider.getEventTypes();
        if (events) {
            printf("  %s: %s (type '%s <id>' for details)\n", QdpCmd::color.key("Incoming Events"),
                (foldl $1 + ", " + $2, keys events), QdpCmd::color.key("/event"));
        }
    }

    private formatConnectionInfo(hash<auto> info) {
        # Format HTTP/2 info if available
        if (info.hasKey("http2")) {
            string protocol = info.http2 ? "HTTP/2 (RFC 8441)" : "HTTP/1.1";
            printf("  %s: %s\n", QdpCmd::color.key("Protocol"), QdpCmd::color.info(protocol));
        }
        # Format peer info (remote endpoint)
        if (info.peer) {
            string peer_str = info.peer.hostname ?? info.peer.address;
            if (info.peer.port) {
                peer_str += ":" + info.peer.port;
            }
            if (info.peer.hostname && info.peer.address && info.peer.address != info.peer.hostname) {
                peer_str += " (" + info.peer.address + ")";
            }
            printf("  %s: %s\n", QdpCmd::color.key("Peer"), peer_str);
        }
        # Format local socket info
        if (info.socket.port) {
            printf("  %s: %d\n", QdpCmd::color.key("Local Port"), info.socket.port);
        }
    }

    private showMessageInfo(AbstractDataProvider provider, string msg_id) {
        if (!msg_id.val()) {
            printf("%s: usage: /msg <message-id>; valid: %s\n", QdpCmd::color.error("ERROR"),
                (foldl $1 + ", " + $2, keys mmap));
            return;
        }
        *hash<DataProviderMessageInfo> info;
        try {
            info = provider.getMessageInfo(msg_id);
        } catch (hash<ExceptionInfo> ex) {
            printf("%s: %s\n", QdpCmd::color.error("ERROR"), ex.desc);
            return;
        }
        if (!info) {
            printf("%s: unknown message '%s'; valid: %s\n", QdpCmd::color.error("ERROR"),
                msg_id, (foldl $1 + ", " + $2, keys mmap));
            return;
        }
        QdpCmd::showType(provider, msg_id, info);
    }

    private showEventInfo(AbstractDataProvider provider, string event_id) {
        if (!event_id.val()) {
            *hash<string, hash<DataProviderMessageInfo>> events = provider.getEventTypes();
            printf("%s: usage: /event <event-id>; valid: %s\n", QdpCmd::color.error("ERROR"),
                events ? (foldl $1 + ", " + $2, keys events) : "(none)");
            return;
        }
        *hash<DataProviderMessageInfo> info;
        try {
            info = provider.getEventInfo(event_id);
        } catch (hash<ExceptionInfo> ex) {
            printf("%s: %s\n", QdpCmd::color.error("ERROR"), ex.desc);
            return;
        }
        if (!info) {
            *hash<string, hash<DataProviderMessageInfo>> events = provider.getEventTypes();
            printf("%s: unknown event '%s'; valid: %s\n", QdpCmd::color.error("ERROR"),
                event_id, events ? (foldl $1 + ", " + $2, keys events) : "(none)");
            return;
        }
        QdpCmd::showType(provider, event_id, info);
    }

    private showAllMessages() {
        if (!mmap) {
            printf("No messages available for this provider\n");
            return;
        }
        printf("%s (type '%s <id>' for type details)\n", QdpCmd::color.bold("SUPPORTED MESSAGES"),
            QdpCmd::color.key("/msg"));
        foreach hash<auto> msg in (mmap.pairIterator()) {
            string desc = msg.value.desc ?? "(no description)";
            printf("  %s %s\n", QdpCmd::color.dim("→"), QdpCmd::color.key(msg.key));
            printf("    %s\n", desc);
        }
    }

    private showAllEvents() {
        if (!emap) {
            printf("No events available for this provider\n");
            return;
        }
        printf("%s (type '%s <id>' for type details)\n", QdpCmd::color.bold("SUPPORTED EVENTS"),
            QdpCmd::color.key("/event"));
        foreach hash<auto> evt in (emap.pairIterator()) {
            string desc = evt.value.desc ?? "(no description)";
            printf("  %s %s\n", QdpCmd::color.dim("→"), QdpCmd::color.key(evt.key));
            printf("    %s\n", desc);
        }
    }

    #! Hints callback — shows inline argument hints while typing
    private *string hintsForInput(string input) {
        try {
            # Slash command argument hints
            if (input[0] == "/") {
                if (input == "/" || "/use".equalPartial(input)) {
                    return " <msg-id>";
                }
                if ("/send".equalPartial(input)) {
                    return " <msg-id> <data>";
                }
                if ("/msg".equalPartial(input)) {
                    return " <msg-id>";
                }
                if ("/event".equalPartial(input)) {
                    return " <event-id>";
                }
                if ("/format".equalPartial(input)) {
                    return " <json|yaml|qore>";
                }
                if ("/history".equalPartial(input)) {
                    return " [search <pat> | clear | delete <n>]";
                }
                return;
            }

            # Empty input hint
            if (!input.val()) {
                return " type data to send or /help";
            }

            # Bare data input — show schema hint for active message type
            if (active_msgid) {
                if (!schema_hints.hasKey(active_msgid)) {
                    *hash<DataProviderMessageInfo> info = mmap{active_msgid};
                    if (info) {
                        AbstractDataProviderType type = info.type;
                        *hash<string, AbstractDataField> fields = type.getFields();
                        if (fields) {
                            list<string> parts = ();
                            foreach hash<auto> f in (fields.pairIterator()) {
                                parts += f.key + ": " + f.value.getType().getName();
                            }
                            schema_hints{active_msgid} = " {" + (foldl $1 + ", " + $2, parts) + "}";
                        } else {
                            schema_hints{active_msgid} = " (" + type.getName() + ")";
                        }
                    }
                }
                *string hint = schema_hints{active_msgid};
                if (hint) {
                    # Truncate if too long for terminal
                    int cols = Linenoise::columns();
                    int avail = cols - input.length() - 1;
                    if (avail > 3 && hint.length() > avail) {
                        hint = hint.substr(0, avail - 3) + "...";
                    }
                    return avail > 3 ? hint : NOTHING;
                }
            }
        } catch () {
            # Never crash from hints
        }
    }

    #! Syntax highlighting callback — colorizes input
    private string syntaxHighlight(string input) {
        try {
            # Slash commands: command name in cyan
            if (input[0] == "/") {
                # Find end of command name
                int sp = index(input, " ");
                if (sp > 0) {
                    return "\033[36m" + input.substr(0, sp) + "\033[0m" + input.substr(sp);
                }
                return "\033[36m" + input + "\033[0m";
            }

            # JSON mode: JSON-specific highlighting
            if (input_format == "json") {
                string result = input;
                # Keys ("key":) → cyan (key + colon together)
                result = regex_subst(result, "(\"[^\"]*\")\\s*:", "\033[36m$1\033[0m:", RE_Global);
                # Value strings (not already colored as keys) → yellow
                # Match quoted strings not preceded by escape codes
                result = regex_subst(result, "(?<!\033\\[0m)(\"[^\"]*\")", "\033[33m$1\033[0m",
                    RE_Global);
                # true/false/null → magenta
                result = regex_subst(result, "\\b(true|false|null)\\b", "\033[35m$&\033[0m",
                    RE_Global);
                # Numbers → bright blue
                result = regex_subst(result, "(?<!\\[)\\b\\d+(\\.\\d+)?\\b", "\033[94m$&\033[0m",
                    RE_Global);
                return result;
            }

            # YAML mode: skip highlighting (too many edge cases for simple regex)
            if (input_format == "yaml") {
                return input;
            }

            # Qore mode: colorize value literals
            string result = input;

            # Double-quoted strings → yellow
            result = regex_subst(result, "\"[^\"]*\"", "\033[33m$&\033[0m", RE_Global);
            # Single-quoted strings → yellow
            result = regex_subst(result, "'[^']*'", "\033[33m$&\033[0m", RE_Global);
            # Special values → magenta
            result = regex_subst(result, "\\b(True|False|NOTHING)\\b", "\033[35m$&\033[0m",
                RE_Global);
            # Numbers → bright blue
            result = regex_subst(result, "\\b\\d+(\\.\\d+)?\\b", "\033[94m$&\033[0m", RE_Global);

            return result;
        } catch () {
            return input;
        }
    }

    softlist<string> completion(string str) {
        list<string> rv = ();

        # For empty input, suggest slash commands
        if (!str.val()) {
            rv += keys Commands;
            return rv;
        }

        # After "/use " or "/send ", complete with message IDs
        if (str =~ /^\/use\s+/) {
            string prefix = trim(str.substr(4));
            foreach string msg in (keys mmap) {
                if (!prefix.val() || msg.equalPartial(prefix)) {
                    rv += "/use " + msg;
                }
            }
            return rv;
        }
        if (str =~ /^\/send\s+/) {
            string prefix = trim(str.substr(5));
            # Only complete the message ID part (before any space in the rest)
            if (prefix !~ /\s/) {
                foreach string msg in (keys mmap) {
                    if (!prefix.val() || msg.equalPartial(prefix)) {
                        rv += "/send " + msg + " ";
                    }
                }
            }
            return rv;
        }

        # After "/msg ", complete with message IDs
        if (str =~ /^\/msg\s+/) {
            string prefix = trim(str.substr(4));
            foreach string msg in (keys mmap) {
                if (!prefix.val() || msg.equalPartial(prefix)) {
                    rv += "/msg " + msg;
                }
            }
            return rv;
        }

        # After "/event ", complete with event IDs
        if (str =~ /^\/event\s+/) {
            string prefix = trim(str.substr(6));
            if (emap) {
                foreach string evt in (keys emap) {
                    if (!prefix.val() || evt.equalPartial(prefix)) {
                        rv += "/event " + evt;
                    }
                }
            }
            return rv;
        }

        # After "/format ", complete with available formats
        if (str =~ /^\/format\s+/) {
            string prefix = trim(str.substr(7));
            list<string> formats = ("qore",);
            formats += "json";
%ifndef NoYaml
            formats += "yaml";
%endif
            foreach string fmt in (formats) {
                if (!prefix.val() || fmt.equalPartial(prefix)) {
                    rv += "/format " + fmt;
                }
            }
            return rv;
        }

        # After "/history ", complete with subcommands
        if (str =~ /^\/history\s+/) {
            string prefix = trim(str.substr(8));
            foreach string subcmd in ("search", "clear", "delete") {
                if (!prefix.val() || subcmd.equalPartial(prefix)) {
                    rv += "/history " + subcmd + " ";
                }
            }
            return rv;
        }

        # Complete slash command names
        if (str[0] == "/") {
            foreach string cmd in (keys Commands) {
                if (cmd.equalPartial(str)) {
                    rv += cmd;
                }
            }
            return rv;
        }

        return rv;
    }
}

class WebhookHandler inherits RestHandler {
    private {
        string rest_method;
        string root_path;
        code callback;

        static bool cors_enable = DefaultCorsEnable;
        static *softlist<string> cors_accept_origin;
        static *string cors_allow_methods = foldl $1 + ", " + $2, DefaultCorsAllowMethods;
        static softstring cors_max_age = DefaultCorsMaxAge;
        static *string cors_allow_headers = foldl $1 + ", " + $2, DefaultCorsAllowHeaders;
        static bool cors_allow_credentials = DefaultCorsAllowCredentials;
        static bool cors_accept_all_origins = DefaultCorsAcceptAllOrigins;
        static hash<string, bool> cors_origin_map;

        const DefaultCorsEnable = True;
        const DefaultCorsAllowMethods = ("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS");
        const DefaultCorsMaxAge = 9999999;
        const DefaultCorsAllowHeaders = (
            "Content-Type", "content-type", "Content-Language", "content-language",
            "Accept", "Accept-Language", "Authorization", "Qorus-Token", "Qorus-Client-Time-Zone",
        );
        const DefaultCorsAllowCredentials = True;
        const DefaultCorsAcceptAllOrigins = True;
    }

    constructor(string method, string path, code callback) : RestHandler() {
        rest_method = method;
        root_path = (path =~ /^\//) ? path[1..] : path;
        self.callback = callback;
    }

    removeRootPath(reference<string> path) {
        if (path.startsWith(root_path)) {
            splice path, 0, root_path.size();
        }
    }

    hash<HttpHandlerResponseInfo> get(hash<auto> cx, *hash<auto> ah) {
        return callWebhook(cx, ah);
    }

    hash<HttpHandlerResponseInfo> post(hash<auto> cx, *hash<auto> ah) {
        return callWebhook(cx, ah);
    }

    hash<HttpHandlerResponseInfo> put(hash<auto> cx, *hash<auto> ah) {
        return callWebhook(cx, ah);
    }

    hash<HttpHandlerResponseInfo> patch(hash<auto> cx, *hash<auto> ah) {
        return callWebhook(cx, ah);
    }

    hash<HttpHandlerResponseInfo> del(hash<auto> cx, *hash<auto> ah) {
        return callWebhook(cx, ah);
    }

    hash<HttpResponseInfo> handleRequest(HttpListenerInterface listener, Socket s, hash<auto> cx, hash<auto> hdr,
            *data b) {
        #logDebug("Webhook headers: %Y", hdr);

        # handle OPTIONS requests
        if (hdr.method == "OPTIONS" && (*hash<auto> cors_hdrs = getCorsResponseHeaders(cx))) {
            # return a CORS response
            return AbstractHttpRequestHandler::makeResponse(200, NOTHING, cors_hdrs);
        }

        # check for valid method
        if (hdr.method != rest_method) {
            # get rest class name
            string path = cx.url.path ?? "";
            removeRootPath(\path);
            return AbstractHttpRequestHandler::makeResponse(405, sprintf("HTTP method %y is not supported with URI "
                "path %y; supported method: %s", hdr.method, path, rest_method), getCorsResponseHeaders(cx) +
                {"Allow": rest_method});
        }

        cx.sctx.listener = listener;
        hash<HttpResponseInfo> rv = RestHandler::handleRequest(listener, s, cx, hdr, b);
        if (!rv.hdr."Access-Control-Allow-Origin") {
            rv.hdr += getCorsResponseHeaders(cx);
        }
        return rv;
    }

    hash<HttpHandlerResponseInfo> callWebhook(hash<auto> cx, *hash<auto> ah) {
        logInfo("Webhook %y called", root_path);
        logDebug("Webhook %y args: %y", root_path, ah);
        on_error QdpCmd::http.logError("%s", get_exception_string($1));
        try {
            return <HttpHandlerResponseInfo>{
                "code": 200,
                "body": callback(ah),
            };
        } catch (hash<ExceptionInfo> ex) {
            QdpCmd::http.logError("Webhook %y args: %y error: %s", root_path, ah, get_exception_string(ex));
            return <HttpHandlerResponseInfo>{
                "code": 500,
                "body": sprintf("%s: %s", ex.err, ex.desc),
            };
        }
    }

    private hash<HttpHandlerResponseInfo> returnRestException(hash<ExceptionInfo> ex) {
        try {
            if (ex.arg.typeCode() == NT_OBJECT) {
                remove ex.arg;
            }
        } catch (hash<ExceptionInfo> ex0) {
            remove ex.arg;
        }
        if (ex.err =~ /-ARG-ERROR$/) {
            return <HttpHandlerResponseInfo>{
                "code": 400,
                "body": ex.desc,
            };
        }
        if (ex.err == "AUTHORIZATION-ERROR" || ex.err =~ /-ACCESS-ERROR$/) {
            return <HttpHandlerResponseInfo>{
                "code": 403,
                "body": ex,
            };
        }
        if (ex.err == "REST-NOT-FOUND-ERROR") {
            return <HttpHandlerResponseInfo>{
                "code": 404,
                "body": ex.desc,
            };
        }
        # for all other errors, return the standard "409 Conflict" response
        return RestHandler::returnRestException(ex);
    }

    private *hash<auto> errorResponseHeaders(hash<auto> cx) {
        return getCorsResponseHeaders(cx);
    }

    static *hash<auto> getCorsResponseHeaders(hash<auto> cx) {
        bool explicit_match;
        if (!WebhookHandler::corsOriginOk(cx, \explicit_match)) {
            return;
        }
        return WebhookHandler::getCorsResponseHeadersIntern(cx, explicit_match);
    }

    static private hash<auto> getCorsResponseHeadersIntern(hash<auto> cx, *bool explicit_match) {
        hash<auto> rv;
        # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
        # if the server supports clients from multiple origins, it must return the origin for the specific client
        # making the request
        if (cx.hdr.origin && !cors_accept_all_origins) {
            rv = {
                "Access-Control-Allow-Origin": cx.hdr.origin,
                "Vary": "Origin",
            };
        } else {
            rv = {
                "Access-Control-Allow-Origin": "*",
            };
        }
        # return other headers for preflight (OPTIONS) requests
        if (cx.hdr.method == "OPTIONS") {
            rv += {
                "Access-Control-Allow-Methods": cors_allow_methods,
                "Access-Control-Max-Age": cors_max_age,
            };
            if (cors_allow_headers) {
                rv."Access-Control-Allow-Headers" = cors_allow_headers;
            }
        }
        if (cors_allow_credentials) {
            rv."Access-Control-Allow-Credentials" = "true";
        }
        return rv;
    }

    static bool corsOriginOk(hash<auto> cx, *reference<bool> explicit_match) {
        if (!cors_enable) {
            return False;
        }
        if (cors_accept_all_origins) {
            return True;
        }
        if (cors_origin_map{cx.hdr.origin}) {
            explicit_match = True;
            return True;
        }
        return False;
    }

    static corsUpdateOption(string opt, auto value) {
        switch (opt) {
            case "cors-enable":
                cors_enable = value;
                break;

            case "cors-allow-origin": {
                cors_accept_origin = value;
                cors_accept_all_origins = False;
                foreach string origin in (cors_accept_origin) {
                    if (origin == "*") {
                        cors_accept_all_origins = True;
                    }
                    cors_origin_map{origin} = True;
                }
                break;
            }

            case "cors-allow-methods":
                cors_allow_methods = foldl $1 + ", " + $2, value;
                break;

            case "cors-max-age":
                cors_max_age = value.toString();
                break;

            case "cors-allow-headers":
                cors_allow_headers = foldl $1 + ", " + $2, value;
                break;

            case "cors-allow-credentials":
                cors_allow_credentials = value;
                break;
        }
    }
}
