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

# @file qore-data-provider-i18n extracts source-owned provider presentation catalogs

/*  Copyright 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 DataProvider
%requires FsUtil
%requires i18n
%requires json
%requires Util

%exec-class QoreDataProviderI18nCmd

class QoreDataProviderI18nCmd {
    public {
        const Version = "0.1";
        const Opts = {
            "output":  "o,output=s",
            "module":  "m,module=s@",
            "owner":   "owner=s@",
            "app":     "a,app=s@",
            "check":   "check",
            "check_tree": "check-tree",
            "check_source_tree": "check-source-tree",
            "update_source_tree": "update-source-tree",
            "require_standard_locales": "require-standard-locales",
            "require_complete_locales": "require-complete-locales",
            "verbose": "v,verbose:i+",
            "help":    "h,help",
        };
    }

    private {
        Util::TerminalColor color;
    }

    constructor() {
        bool no_color = removeNoColorOption();
        color = new Util::TerminalColor(!no_color);
        GetOpt g(Opts);
        hash<auto> opt = g.parse3(\ARGV);
        if (opt.help) {
            usage();
            return;
        }
        if (ARGV) {
            fail("unexpected positional arguments: " + ARGV.join(" "));
        }
        if (!opt.output.val()) {
            fail("--output is required");
        }

        try {
            run(opt);
        } catch (hash<ExceptionInfo> ex) {
            stderr.printf("%s %s: %s\n", color.error("ERROR:"), ex.err,
                ex.desc);
            exit(1);
        }
    }

    private run(hash<auto> opt) {
        if ((opt.require_standard_locales || opt.require_complete_locales)
                && !opt.check
                && !opt.check_tree && !opt.check_source_tree) {
            fail("--require-standard-locales and --require-complete-locales require a check mode");
        }
        list<string> required_locales = opt.require_standard_locales
            ? DataProviderPresentation::StandardTranslationLocales : ();
        if (opt.update_source_tree) {
            if (opt.check || opt.check_tree || opt.check_source_tree
                    || opt.app) {
                fail("--update-source-tree cannot be combined with a check mode or --app");
            }
            updateSourceTree(opt.output,
                cast<list<string>>(opt.module ?? ()),
                cast<list<string>>(opt.owner ?? ()), opt.verbose);
            return;
        }
        if (opt.check_source_tree) {
            if (opt.app) {
                fail("--check-source-tree cannot be combined with --app");
            }
            checkSourceTree(opt.output,
                cast<list<string>>(opt.module ?? ()),
                cast<list<string>>(opt.owner ?? ()), required_locales,
                opt.require_complete_locales ?? False, opt.verbose);
            return;
        }

        if (opt.check_tree) {
            if (opt.module || opt.owner || opt.app) {
                fail("--check-tree cannot be combined with --module, --owner, or --app");
            }
            checkTree(opt.output, required_locales,
                opt.require_complete_locales ?? False, opt.verbose);
            return;
        }

        if (opt.owner && opt.app) {
            fail("--owner cannot be combined with --app");
        }

        hash<string, bool> modules_to_load = map {$1: True},
            cast<list<string>>(opt.module ?? ())
                + cast<list<string>>(opt.owner ?? ());
        foreach string module_name in (sort(keys modules_to_load)) {
            if (opt.verbose) {
                printf("loading provider module %s\n", color.key(module_name));
            }
            load_module(module_name);
        }

        hash<string, hash<auto>> catalogs = {};
        hash<string, bool> app_names;
        if (opt.owner) {
            foreach string owner in (cast<list<string>>(opt.owner)) {
                foreach hash<auto> contribution in (
                        DataProviderActionCatalog::getPresentationContributionsForModule(
                            owner)) {
                    requireSourceLocales(contribution.app,
                        contribution.actions, owner);
                    app_names{contribution.app.name} = True;
                    mergeCatalogs(\catalogs,
                        DataProviderPresentation::buildSourceCatalogs(
                            contribution.app, contribution.actions,
                            contribution.include_app));
                }
            }
        } else {
            hash<string, hash<auto>> app_map = {};
            foreach hash<auto> app in (
                    DataProviderActionCatalog::getAllApps()) {
                app_map{app.name} = app;
            }
            list<string> selected_apps = opt.app
                ? cast<list<string>>(opt.app) : sort(keys app_map);
            foreach string app_name in (selected_apps) {
                if (!exists app_map{app_name}) {
                    throw "DATA-PROVIDER-I18N-ERROR",
                        sprintf("provider application %y is not registered",
                            app_name);
                }
                app_names{app_name} = True;
                hash<auto> app = app_map{app_name};
                list<hash<auto>> actions =
                    DataProviderActionCatalog::getActions(app_name, False);
                requireSourceLocales(app, actions);
                mergeCatalogs(\catalogs,
                    DataProviderPresentation::buildSourceCatalogs(app,
                        actions));
            }
        }
        if (!catalogs) {
            throw "DATA-PROVIDER-I18N-ERROR",
                opt.owner
                    ? sprintf("owner module(s) %y have no registered presentation contributions",
                        cast<list<string>>(opt.owner))
                    : "no provider applications are registered";
        }

        int stale = 0;
        foreach string domain in (sort(keys catalogs)) {
            # Reuse the native validation boundary before treating a domain as
            # a directory name. An empty search path performs no file access.
            list<string> validated_catalog_files = I18n::discover_catalog_files(domain,
                DataProviderPresentation::RootLocale,
                {"search_path": ()});
            string path = join_paths(opt.output, domain, "root.json");
            string data = make_json(catalogs{domain}, JGF_ADD_FORMATTING)
                + "\n";
            if (opt.check) {
                if (!is_readable(path)
                        || parse_json(ReadOnlyFile::readTextFile(path))
                            != catalogs{domain}) {
                    ++stale;
                    stderr.printf("%s %s\n", color.error("STALE:"), path);
                }
                stale += checkTranslations(domain,
                    catalogs{domain}.locales.root.messages, opt.output,
                    required_locales,
                    opt.require_complete_locales ?? False,
                    opt.verbose);
                stale += checkRequiredTranslationLocales(domain, opt.output,
                    required_locales);
                continue;
            }
            mkdir_ex(dirname(path), 0755, True);
            writeFile(path, data);
            if (opt.verbose) {
                printf("wrote %s (%d messages)\n", color.key(path),
                    catalogs{domain}.locales.root.messages.size());
            }
        }
        if (opt.check && !opt.app) {
            stale += checkOrphanedCatalogs(opt.output, catalogs);
        }
        if (stale) {
            exit(2);
        }
        printf("%s %d app(s), %d catalog domain(s)\n",
            opt.check ? "verified" : "extracted", app_names.size(),
            catalogs.size());
    }

    private checkTree(string output, list<string> required_locales,
            bool require_complete_locales, *int verbose) {
        list<hash<auto>> roots = ();
        collectRootCatalogs(output, \roots);
        if (!roots) {
            throw "DATA-PROVIDER-I18N-ERROR", sprintf(
                "no source-owned provider root catalogs found below %y",
                output);
        }

        int stale = 0;
        int translation_count = 0;
        hash<string, list<hash<auto>>> domain_roots;
        foreach hash<auto> root in (roots) {
            domain_roots{root.domain} += root;
        }
        foreach string domain in (sort(keys domain_roots)) {
            hash<auto> root_messages;
            list<string> search_roots = ();
            hash<string, bool> seen_search_roots;
            foreach hash<auto> root in (domain_roots{domain}) {
                if (!seen_search_roots{root.search_root}) {
                    seen_search_roots{root.search_root} = True;
                    search_roots += root.search_root;
                }
                hash<auto> catalog = I18n::load_native_catalog(root.path);
                I18n::MessageCatalog validated(catalog,
                    {"literal_messages": True});
                if (sort(keys catalog.locales)
                        != (DataProviderPresentation::RootLocale,)) {
                    ++stale;
                    stderr.printf("%s %s must contain only locale %y\n",
                        color.error("STALE:"), root.path,
                        DataProviderPresentation::RootLocale);
                    continue;
                }
                foreach hash<auto> entry in (
                        catalog.locales.root.messages.pairIterator()) {
                    if (exists root_messages{entry.key}
                            && root_messages{entry.key} != entry.value) {
                        ++stale;
                        stderr.printf("%s %s: conflicting owner fragment for message %y\n",
                            color.error("STALE:"), root.path, entry.key);
                        continue;
                    }
                    root_messages{entry.key} = entry.value;
                }
                if (verbose) {
                    printf("verified %s\n", color.key(root.path));
                }
            }
            hash<auto> result =
                DataProviderPresentation::inspectTranslationCatalogs(
                    domain, root_messages,
                    {"search_path": search_roots});
            translation_count += result.translation_count;
            foreach hash<auto> issue in (result.issues) {
                ++stale;
                stderr.printf("%s %s%s: %s\n", color.error("STALE:"),
                    issue.path, issue.message_id.val()
                        ? ": " + issue.message_id : "", issue.reason);
            }
            stale += checkCompleteTranslationLocales(domain, root_messages,
                result, output,
                required_locales, require_complete_locales);
            foreach string search_root in (search_roots) {
                stale += checkRequiredTranslationLocales(domain,
                    search_root, required_locales);
            }
        }
        if (stale) {
            exit(2);
        }
        printf("verified %d catalog domain(s), %d translation(s)\n",
            domain_roots.size(), translation_count);
    }

    private checkSourceTree(string output, list<string> extra_modules,
            list<string> explicit_owners, list<string> required_locales,
            bool require_complete_locales, *int verbose) {
        list<string> source_roots = providerSourceRoots(output);
        list<hash<auto>> roots = ();
        foreach string source_root in (source_roots) {
            collectRootCatalogs(source_root, \roots);
        }
        if (!roots) {
            throw "DATA-PROVIDER-I18N-ERROR", sprintf(
                "no source-owned provider root catalogs found below %y",
                output);
        }

        hash<string, bool> owner_modules = map {$1: True}, explicit_owners;
        # Catalog-derived discovery cannot see a newly added provider module
        # until its first root catalog exists.  Discover exact source-level
        # registration owners as well, so --check-source-tree reports that
        # missing catalog instead of silently accepting an incomplete tree.
        foreach string source_root in (source_roots) {
            collectProviderSourceOwners(source_root, \owner_modules);
        }
        list<hash<auto>> unresolved_roots = ();
        list<hash<auto>> owned_roots = ();
        foreach hash<auto> root in (roots) {
            *string module_name = sourceOwnerModule(root.search_root);
            if (module_name.val()) {
                owner_modules{module_name} = True;
                root.owner = module_name;
                owned_roots += root;
            } else {
                unresolved_roots += root;
            }
        }
        if (unresolved_roots && explicit_owners.size() != 1) {
            throw "DATA-PROVIDER-I18N-ERROR", sprintf(
                "cannot infer an owner module for catalog %y; pass exactly one --owner for a noncanonical source tree",
                unresolved_roots.first().path);
        }
        if (unresolved_roots) {
            string owner = explicit_owners.first();
            foreach hash<auto> root in (unresolved_roots) {
                root.owner = owner;
                owned_roots += root;
            }
        }
        if (!owner_modules) {
            throw "DATA-PROVIDER-I18N-ERROR",
                "no provider owner modules were discovered";
        }

        hash<string, bool> modules_to_load = owner_modules;
        foreach string module_name in (extra_modules) {
            modules_to_load{module_name} = True;
        }
        foreach string module_name in (sort(keys modules_to_load)) {
            if (verbose) {
                printf("loading provider module %s\n",
                    color.key(module_name));
            }
            load_module(module_name);
        }

        hash<string, hash<string, hash<auto>>> owner_catalogs;
        foreach string owner in (sort(keys owner_modules)) {
            owner_catalogs{owner} = moduleCatalogs(owner);
        }

        int stale = 0;
        int translation_count = 0;
        hash<string, hash<string, bool>> seen;
        foreach hash<auto> root in (owned_roots) {
            if (seen{root.owner}{root.domain}) {
                ++stale;
                stderr.printf("%s %s: duplicate catalog domain %y for owner module %y\n",
                    color.error("STALE:"), root.path, root.domain,
                    root.owner);
                continue;
            }
            seen{root.owner}{root.domain} = True;
            hash<auto> catalog = I18n::load_native_catalog(root.path);
            I18n::MessageCatalog validated(catalog,
                {"literal_messages": True});
            if (sort(keys catalog.locales)
                    != (DataProviderPresentation::RootLocale,)) {
                ++stale;
                stderr.printf("%s %s must contain only locale %y\n",
                    color.error("STALE:"), root.path,
                    DataProviderPresentation::RootLocale);
                continue;
            }
            if (!exists owner_catalogs{root.owner}{root.domain}) {
                ++stale;
                stderr.printf("%s %s: module %y does not own catalog domain %y\n",
                    color.error("ORPHANED:"), root.path, root.owner,
                    root.domain);
                continue;
            }
            if (catalog != owner_catalogs{root.owner}{root.domain}) {
                ++stale;
                stderr.printf("%s %s\n", color.error("STALE:"),
                    root.path);
            }
            hash<auto> result =
                DataProviderPresentation::inspectTranslationCatalogs(
                    root.domain,
                    owner_catalogs{root.owner}{root.domain}.locales.root.messages,
                    {"search_path": (root.search_root,)});
            translation_count += result.translation_count;
            foreach hash<auto> issue in (result.issues) {
                ++stale;
                stderr.printf("%s %s%s: %s\n", color.error("STALE:"),
                    issue.path, issue.message_id.val()
                        ? ": " + issue.message_id : "", issue.reason);
            }
            stale += checkCompleteTranslationLocales(root.domain,
                owner_catalogs{root.owner}{root.domain}.locales.root.messages,
                result, root.search_root, required_locales,
                require_complete_locales);
            stale += checkRequiredTranslationLocales(root.domain,
                root.search_root, required_locales);
            if (verbose) {
                printf("verified %s\n", color.key(root.path));
            }
        }
        foreach string owner in (sort(keys owner_catalogs)) {
            foreach string domain in (sort(keys owner_catalogs{owner})) {
                if (!seen{owner}{domain}) {
                    ++stale;
                    stderr.printf("%s owner module %y catalog domain %y\n",
                        color.error("MISSING:"), owner, domain);
                }
            }
        }

        if (stale) {
            exit(2);
        }
        printf("verified %d owner module(s), %d catalog domain(s), %d translation(s)\n",
            owner_modules.size(), roots.size(), translation_count);
    }

    #! Regenerates every source-owned root catalog after loading the complete owner set once
    private updateSourceTree(string output, list<string> extra_modules,
            list<string> explicit_owners, *int verbose) {
        list<string> source_roots = providerSourceRoots(output);
        list<hash<auto>> roots = ();
        foreach string source_root in (source_roots) {
            collectRootCatalogs(source_root, \roots);
        }
        if (!roots) {
            throw "DATA-PROVIDER-I18N-ERROR", sprintf(
                "no source-owned provider root catalogs found below %y",
                output);
        }

        hash<string, bool> owner_modules = map {$1: True},
            explicit_owners;
        foreach string source_root in (source_roots) {
            collectProviderSourceOwners(source_root, \owner_modules);
        }
        list<hash<auto>> owned_roots = ();
        foreach hash<auto> root in (roots) {
            *string module_name = sourceOwnerModule(root.search_root);
            if (!module_name.val()) {
                if (explicit_owners.size() != 1) {
                    throw "DATA-PROVIDER-I18N-ERROR", sprintf(
                        "cannot infer an owner module for catalog %y; pass exactly one --owner for a noncanonical source tree",
                        root.path);
                }
                module_name = explicit_owners.first();
            }
            owner_modules{module_name} = True;
            root.owner = module_name;
            owned_roots += root;
        }

        hash<string, bool> modules_to_load = owner_modules;
        foreach string module_name in (extra_modules) {
            modules_to_load{module_name} = True;
        }
        foreach string module_name in (sort(keys modules_to_load)) {
            if (verbose) {
                printf("loading provider module %s\n",
                    color.key(module_name));
            }
            load_module(module_name);
        }

        hash<string, hash<string, hash<auto>>> owner_catalogs;
        foreach string owner in (sort(keys owner_modules)) {
            owner_catalogs{owner} = moduleCatalogs(owner);
        }

        # Validate the complete owner/domain mapping before touching any file.
        # This prevents a late duplicate, orphan, or new-domain error from
        # leaving an otherwise repairable tree only partly regenerated.
        hash<string, hash<string, bool>> seen;
        hash<string, hash<auto>> roots_by_path;
        foreach hash<auto> root in (owned_roots) {
            if (seen{root.owner}{root.domain}) {
                throw "DATA-PROVIDER-I18N-ERROR", sprintf(
                    "duplicate catalog domain %y for owner module %y",
                    root.domain, root.owner);
            }
            seen{root.owner}{root.domain} = True;
            if (!exists owner_catalogs{root.owner}{root.domain}) {
                throw "DATA-PROVIDER-I18N-ERROR", sprintf(
                    "catalog %y is orphaned; module %y no longer owns domain %y",
                    root.path, root.owner, root.domain);
            }
            roots_by_path{root.path} = root;
        }
        foreach string owner in (sort(keys owner_catalogs)) {
            foreach string domain in (sort(keys owner_catalogs{owner})) {
                if (!seen{owner}{domain}) {
                    throw "DATA-PROVIDER-I18N-ERROR", sprintf(
                        "owner module %y has new catalog domain %y with no existing canonical source-tree location",
                        owner, domain);
                }
            }
        }
        int written = 0;
        foreach string path in (sort(keys roots_by_path)) {
            hash<auto> root = roots_by_path{path};
            string data = make_json(
                owner_catalogs{root.owner}{root.domain},
                JGF_ADD_FORMATTING) + "\n";
            writeFile(path, data);
            ++written;
            if (verbose) {
                printf("wrote %s (%d messages)\n", color.key(path),
                    owner_catalogs{root.owner}{root.domain}.locales.root.messages.size());
            }
        }
        printf("updated %d owner module(s), %d catalog domain(s)\n",
            owner_modules.size(), written);
    }

    #! Returns the production library roots below a source-tree path
    /** A repository can contain examples, tests, build trees, and other Qore
        sources that deliberately exercise provider registration APIs without
        defining production provider metadata.  Repository-level verification
        therefore follows the structural Qore library layout instead of
        interpreting every source file below the repository as production.

        A narrow library or generated-catalog path has no direct production
        library child, so it remains its own discovery root.  This preserves
        explicit-owner checks for noncanonical trees.

        @param path source-tree path supplied to --output
        @return direct production library roots, or the supplied path
    */
    private list<string> providerSourceRoots(string path) {
        Dir dir();
        if (!dir.chdir(path)) {
            throw "DATA-PROVIDER-I18N-ERROR",
                sprintf("cannot read provider source tree directory %y",
                    path);
        }
        list<string> roots = ();
        foreach string child in (dir.listDirs()) {
            if (child == "qlib" || child.startsWith("qlib-")) {
                roots += path + DirSep + child;
            }
        }
        return roots ? roots : (path,);
    }

    #! Finds provider owner modules before their first catalog exists
    /** Module discovery is based only on exact DataProvider registration API
        calls in Qore module source.  These are technical symbols rather than
        presentation text, and therefore remain language-independent.  Roots
        inferred from canonical catalog layouts are still authoritative for
        modules whose registration is delegated to another source file.

        @param path source-tree path to inspect recursively
        @param owners output set of exact technical module names
    */
    private collectProviderSourceOwners(string path,
            reference<hash<string, bool>> owners) {
        foreach string file in (glob(path + DirSep + "*.qm")) {
            if (!is_file(file)) {
                continue;
            }
            string source = ReadOnlyFile::readTextFile(file);
            bool owns_provider_presentation = False;
            foreach string registration in ((
                    "DataProviderActionCatalog::registerApp(",
                    "DataProviderActionCatalog::registerPendingApp(",
                    "DataProviderActionCatalog::registerAction(",
                    "DataProviderActionCatalog::registerPendingAppAction(")) {
                if (source.find(registration) >= 0) {
                    owns_provider_presentation = True;
                    break;
                }
            }
            if (!owns_provider_presentation) {
                continue;
            }
            string file_name = basename(file);
            owners{file_name.substr(0, file_name.length() - 3)} = True;
        }

        Dir dir();
        if (!dir.chdir(path)) {
            throw "DATA-PROVIDER-I18N-ERROR",
                sprintf("cannot read provider source tree directory %y",
                    path);
        }
        foreach string child in (dir.listDirs()) {
            if (child == "i18n" || child.endsWith(".i18n")
                    || child.startsWith(
                        DataProviderPresentation::CatalogDomainPrefix)) {
                continue;
            }
            collectProviderSourceOwners(path + DirSep + child, \owners);
        }
    }

    private hash<string, hash<auto>> moduleCatalogs(string owner) {
        hash<string, hash<auto>> catalogs = {};
        foreach hash<auto> contribution in (
                DataProviderActionCatalog::getPresentationContributionsForModule(
                    owner)) {
            requireSourceLocales(contribution.app, contribution.actions,
                owner);
            mergeCatalogs(\catalogs,
                DataProviderPresentation::buildSourceCatalogs(
                    contribution.app, contribution.actions,
                    contribution.include_app));
        }
        return catalogs;
    }

    #! Rejects provider presentation whose producer locale is not explicit
    /** Catalog extraction must not silently turn unknown-language prose into
        an unlabelled source catalog.  The native metadata inspector owns
        locale validation; this command only formats exact identities for a
        source-tree diagnostic.
    */
    private requireSourceLocales(hash<auto> app,
            list<hash<auto>> actions, *string owner = NOTHING) {
        list<hash<auto>> issues =
            DataProviderPresentation::inspectSourceLocales(app, actions);
        if (!issues) {
            return;
        }
        list<string> labels = map sprintf("%s %s (%s)", $1.scope,
            $1.scope == "action"
                ? $1.app.toString() + "/" + $1.action.toString()
                : $1.app.toString(), $1.reason), issues;
        throw "DATA-PROVIDER-I18N-ERROR", sprintf(
            "%sprovider presentation source locale validation failed: %s",
            owner.val() ? sprintf("owner module %y: ", owner) : "",
            labels.join(", "));
    }

    private int checkOrphanedCatalogs(string output,
            hash<string, hash<auto>> catalogs) {
        if (!is_dir(output)) {
            return 0;
        }

        hash<string, string> paths;
        Dir dir();
        if (!dir.chdir(output)) {
            throw "DATA-PROVIDER-I18N-ERROR",
                sprintf("cannot read catalog output directory %y", output);
        }
        foreach string name in (dir.listDirs()) {
            if (name.startsWith(
                    DataProviderPresentation::CatalogDomainPrefix)) {
                paths{name} = output + DirSep + name;
            }
        }
        string flat_suffix = "."
            + DataProviderPresentation::RootLocale + ".json";
        foreach string path in (glob(output + DirSep
                + DataProviderPresentation::CatalogDomainPrefix + "*"
                + flat_suffix)) {
            if (!is_file(path)) {
                continue;
            }
            string name = basename(path);
            paths{name.substr(0,
                name.length() - flat_suffix.length())} = path;
        }

        int stale = 0;
        foreach string domain in (sort(keys paths)) {
            if (!exists catalogs{domain}) {
                ++stale;
                stderr.printf("%s %s\n", color.error("ORPHANED:"),
                    paths{domain});
            }
        }
        return stale;
    }

    private collectRootCatalogs(string path,
            reference<list<hash<auto>>> roots) {
        if (!is_dir(path)) {
            throw "DATA-PROVIDER-I18N-ERROR",
                sprintf("catalog tree %y is not a directory", path);
        }
        string name = basename(path);
        if (name == DataProviderPresentation::RootLocale) {
            string domain = basename(dirname(path));
            if (domain.startsWith(
                    DataProviderPresentation::CatalogDomainPrefix)) {
                foreach string fragment in (glob(path + DirSep + "*.json")) {
                    if (is_file(fragment)) {
                        roots += {
                            "domain": domain,
                            "path": fragment,
                            "search_root": dirname(dirname(path)),
                        };
                    }
                }
            }
        }
        string nested_root = path + DirSep
            + DataProviderPresentation::RootLocale + ".json";
        if (name.startsWith(DataProviderPresentation::CatalogDomainPrefix)
                && is_file(nested_root)) {
            roots += {
                "domain": name,
                "path": nested_root,
                "search_root": dirname(path),
            };
        }

        string flat_suffix = "."
            + DataProviderPresentation::RootLocale + ".json";
        foreach string file in (glob(path + DirSep
                + DataProviderPresentation::CatalogDomainPrefix + "*"
                + flat_suffix)) {
            if (!is_file(file)) {
                continue;
            }
            string file_name = basename(file);
            roots += {
                "domain": file_name.substr(0,
                    file_name.length() - flat_suffix.length()),
                "path": file,
                "search_root": path,
            };
        }

        Dir dir();
        if (!dir.chdir(path)) {
            throw "DATA-PROVIDER-I18N-ERROR",
                sprintf("cannot read catalog tree directory %y", path);
        }
        foreach string child in (dir.listDirs()) {
            collectRootCatalogs(path + DirSep + child, \roots);
        }
    }

    private *string sourceOwnerModule(string search_root) {
        string name = basename(search_root);
        if (name == "i18n") {
            string module_dir = dirname(search_root);
            string module_name = basename(module_dir);
            if (is_file(module_dir + DirSep + module_name + ".qm")) {
                return module_name;
            }
        }

        const string suffix = ".i18n";
        if (name.endsWith(suffix)) {
            string module_name = name.substr(0,
                name.length() - suffix.length());
            if (is_file(dirname(search_root) + DirSep + module_name
                    + ".qm")) {
                return module_name;
            }
        }
        return NOTHING;
    }

    private int checkTranslations(string domain, hash<auto> root_messages,
            string output, list<string> required_locales,
            bool require_complete_locales, *int verbose) {
        hash<auto> result =
            DataProviderPresentation::inspectTranslationCatalogs(domain,
                root_messages, {"search_path": (output,)});
        foreach hash<auto> issue in (result.issues) {
            stderr.printf("%s %s%s: %s\n", color.error("STALE:"),
                issue.path, issue.message_id.val()
                    ? ": " + issue.message_id : "", issue.reason);
        }
        if (verbose) {
            printf("checked %d translation(s) for %s\n",
                result.translation_count, color.key(domain));
        }
        return result.issues.size()
            + checkCompleteTranslationLocales(domain, root_messages, result,
                output, required_locales, require_complete_locales);
    }

    #! Reports missing message identities in required translation locales
    /** Partial locale catalogs remain valid by default.  This opt-in policy
        gate is for shipped locale sets that promise complete presentation.
        It compares exact catalog identities only and accepts translations
        identical to their producer source, so brands and cognates are never
        rejected because of their text.
    */
    private int checkCompleteTranslationLocales(string domain,
            hash<auto> root_messages, hash<auto> inspection,
            string search_root, list<string> required_locales,
            bool require_complete_locales) {
        if (!require_complete_locales) {
            return 0;
        }
        list<string> locales = required_locales
            ? required_locales
            : sort(keys inspection.translation_message_ids_by_locale);
        list<string> root_message_ids = sort(keys root_messages);
        int missing = 0;
        foreach string locale in (locales) {
            list<string> message_ids = ();
            if (exists
                    inspection.translation_message_ids_by_locale{locale}) {
                message_ids = cast<list<string>>(
                    inspection.translation_message_ids_by_locale{locale});
            }
            hash<string, bool> available = map {$1: True}, message_ids;
            foreach string message_id in (root_message_ids) {
                if (!available{message_id}) {
                    ++missing;
                    stderr.printf("%s catalog domain %y locale %y below %s: message %y\n",
                        color.error("MISSING:"), domain, locale,
                        search_root, message_id);
                }
            }
        }
        return missing;
    }

    #! Reports standard translation locale files missing from one catalog
    /** Required locales are exact canonical BCP 47 identities supplied by
        policy. Discovery uses the native catalog layouts and never infers a
        language from message text or filenames outside that native boundary.
    */
    private int checkRequiredTranslationLocales(string domain,
            string search_root, list<string> required_locales) {
        if (!required_locales) {
            return 0;
        }
        hash<string, bool> available = map {$1: True},
            DataProviderPresentation::discoverCatalogLocales(domain,
                {"search_path": (search_root,)});
        int missing = 0;
        foreach string locale in (required_locales) {
            if (!available{locale}) {
                ++missing;
                stderr.printf("%s catalog domain %y locale %y below %s\n",
                    color.error("MISSING:"), domain, locale, search_root);
            }
        }
        return missing;
    }

    private mergeCatalogs(reference<hash<string, hash<auto>>> target,
            hash<string, hash<auto>> source) {
        foreach hash<auto> catalog_entry in (source.pairIterator()) {
            string domain = catalog_entry.key;
            hash<auto> source_messages =
                catalog_entry.value.locales.root.messages;
            if (!exists target{domain}) {
                target{domain} = catalog_entry.value;
                continue;
            }
            foreach hash<auto> message in (
                    source_messages.pairIterator()) {
                if (exists target{domain}.locales.root.messages{message.key}
                        && target{domain}.locales.root.messages{message.key}
                            != message.value) {
                    throw "DATA-PROVIDER-I18N-ERROR",
                        sprintf("catalog domain %y has conflicting message "
                            "id %y", domain, message.key);
                }
                target{domain}.locales.root.messages{message.key} =
                    message.value;
            }
        }
    }

    private writeFile(string path, string data) {
        # Write beside the destination and replace it atomically. A process,
        # disk, or serialization failure must leave either the old complete
        # catalog or the new complete catalog, never a truncated JSON file.
        string temporary = path + ".tmp." + get_random_string(12);
        on_exit unlink(temporary);
        File file();
        file.open2(temporary, O_CREAT | O_EXCL | O_WRONLY, 0644);
        file.write(data);
        file.close();
        rename(temporary, path);
    }

    private bool removeNoColorOption() {
        bool no_color = False;
        list<string> args = ();
        foreach string arg in (ARGV) {
            if (arg == "-C" || arg == "--no-color") {
                no_color = True;
            } else {
                args += arg;
            }
        }
        ARGV = args;
        return no_color;
    }

    private fail(string message) {
        stderr.printf("%s %s\n\n", color.error("ERROR:"), message);
        usage();
        exit(1);
    }

    private usage() {
        printf("%s v%s - Extract source-owned data-provider i18n catalogs\n\n",
            color.bold("qore-data-provider-i18n"), Version);
        printf("%s\n", color.bold("USAGE"));
        printf("  qore-data-provider-i18n [options]\n\n");
        printf("%s\n", color.bold("OPTIONS"));
        printf("  -o, --output=DIR   Root output directory (required)\n");
        printf("  -m, --module=MOD   Load provider module; repeatable\n");
        printf("      --owner=MOD    Extract only contributions owned by module; repeatable\n");
        printf("  -a, --app=APP      Extract exact app identifier; repeatable\n");
        printf("      --check        Exit 2 if any generated root or translation is stale\n");
        printf("      --check-tree   Recursively verify catalogs without loading providers\n");
        printf("      --check-source-tree\n");
        printf("                     Load source owners and verify roots and translations\n");
        printf("      --update-source-tree\n");
        printf("                     Load source owners once and rewrite every root catalog\n");
        printf("      --require-standard-locales\n");
        printf("                     Require every standard translation locale in a check\n");
        printf("      --require-complete-locales\n");
        printf("                     Require every checked locale to cover every root message\n");
        printf("  -v, --verbose      Show loaded modules and written files\n");
        printf("  -C, --no-color     Disable colored output\n");
        printf("  -h, --help         Show this help\n");
    }
}
