#!/usr/bin/env node
"use strict";
/**
 * Business CLI runner for dominds
 *
 * Usage:
 *   dominds [subcommand] [options]
 *
 * Subcommands:
 *   webui    - Start WebUI server (default)
 *   tui      - Start Text User Interface
 *   run      - Run task dialog (alias for tui)
 *   read     - Read team configuration
 *   man      - Render toolset manual to stdout
 *   manual   - Alias for man
 *   validate_team_def - Validate explicit team toolset declarations
 *   cert     - Create and inspect local HTTPS certificates
 *   create   - Create a new runtime workspace (rtws) from a template
 *   install  - Install a Dominds App into this rtws
 *   doctor   - Diagnose Dominds App state in this rtws
 *   enable   - Enable an installed Dominds App in this rtws
 *   disable  - Disable an installed Dominds App in this rtws
 *   uninstall- Uninstall a Dominds App from this rtws
 *   update   - Update installed Dominds App(s)
 *   new      - Alias for create
 *   help     - Show help
 *
 * This file is launched by the top-level dominds supervisor.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.configureEnvProxySupport = configureEnvProxySupport;
exports.main = main;
const fs = __importStar(require("fs"));
const http = __importStar(require("node:http"));
const path = __importStar(require("path"));
const runtime_1 = require("./apps/runtime");
const dotenv_1 = require("./bootstrap/dotenv");
const cert_1 = require("./cli/cert");
const create_1 = require("./cli/create");
const disable_1 = require("./cli/disable");
const doctor_1 = require("./cli/doctor");
const enable_1 = require("./cli/enable");
const install_1 = require("./cli/install");
const manual_1 = require("./cli/manual");
const read_1 = require("./cli/read");
const tui_1 = require("./cli/tui");
const uninstall_1 = require("./cli/uninstall");
const update_1 = require("./cli/update");
const validate_team_def_1 = require("./cli/validate-team-def");
const webui_1 = require("./cli/webui");
const process_title_1 = require("./process-title");
const rtws_1 = require("./rtws");
require("./tools/builtins");
function configureEnvProxySupport() {
    const domindsUseEnvProxy = process.env.DOMINDS_USE_ENV_PROXY?.trim();
    if (domindsUseEnvProxy === '0') {
        return;
    }
    try {
        const setGlobalProxyFromEnv = http.setGlobalProxyFromEnv;
        if (typeof setGlobalProxyFromEnv !== 'function') {
            console.error('Error: DOMINDS_USE_ENV_PROXY requires Node.js 24.5+ because http.setGlobalProxyFromEnv() is unavailable.');
            process.exit(1);
        }
        setGlobalProxyFromEnv(process.env);
    }
    catch (err) {
        console.error('Error: invalid proxy environment configuration:', err instanceof Error ? err.message : String(err));
        process.exit(1);
    }
}
function printHelp() {
    console.log(`
Dominds CLI - AI-driven DevOps framework with persistent memory

Usage:
  dominds [-C <dir>] [subcommand] [options]

Global Options:
  -C <dir>            Change runtime workspace directory (handled by the dominds supervisor)

Subcommands:
  webui [options]    Start WebUI server (default)
  tui [options]      Start Text User Interface
  run [options]      Run task dialog (alias for tui)
  read [options]     Read team configuration
  man [options]      Render toolset manual to stdout
  manual [options]   Alias for man
  validate_team_def [options] Validate explicit team toolset declarations
  cert [options]     Create and inspect local HTTPS certificates
  create [options]   Create a new runtime workspace (rtws) from a template
  install [options]  Install a Dominds App into this rtws
  doctor [options]   Read-only diagnosis across manifest/lock/configuration/resolution/handshake
  enable [options]   Enable an installed Dominds App in this rtws
  disable [options]  Disable an installed Dominds App in this rtws
  uninstall [options] Uninstall a Dominds App from this rtws
  update [options]   Update installed Dominds App(s)
  new [options]      Alias for create
  help               Show this help message

Examples:
  dominds                    # Start WebUI server (default)
  dominds webui              # Start WebUI server
  dominds -C /path/to/my-ws webui # Start in specific rtws
  dominds -C ux-rtws webui        # Relative -C is resolved by the supervisor
  dominds tui --help         # Show TUI help
  dominds run task.tsk       # Run task dialog
  dominds read               # Read team configuration
  dominds man ws_read --lang zh --all
  dominds validate_team_def  # Validate toolset references in .minds/team.yaml
  dominds cert create --host 192.168.1.10
  dominds cert status        # Inspect detected LAN HTTPS certificate status
  dominds create web-scaffold my-project   # Create rtws from a template
  dominds doctor @longrun-ai/web-dev       # Diagnose a single app across all app-state layers

Installation:
  pnpm add -g dominds

For detailed help on a specific subcommand:
  dominds <subcommand> --help
`);
}
function printVersion() {
    try {
        const packageJson = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf8'));
        console.log(`dominds v${packageJson.version}`);
    }
    catch {
        console.log('dominds (version unknown)');
    }
}
async function main(argv = process.argv.slice(2)) {
    const args = argv;
    // Handle no arguments - default to webui
    if (args.length === 0) {
        (0, dotenv_1.loadRtwsDotenv)({ cwd: (0, rtws_1.domindsRtwsRootAbs)() });
        configureEnvProxySupport();
        await runSubcommand('webui', []);
        return;
    }
    const subcommand = args[0];
    const subcommandArgs = args.slice(1);
    // Handle help and version flags
    if (subcommand === '-h' || subcommand === '--help' || subcommand === 'help') {
        printHelp();
        process.exit(0);
    }
    if (subcommand === '-v' || subcommand === '--version') {
        printVersion();
        process.exit(0);
    }
    const shouldSkipRtwsSetup = subcommand === 'cert' ||
        subcommandArgs.includes('--help') ||
        (subcommand === 'tui' && subcommandArgs.includes('-h')) ||
        (subcommand === 'run' && subcommandArgs.includes('-h')) ||
        (subcommand === 'read' && subcommandArgs.includes('-h')) ||
        (subcommand === 'validate_team_def' && subcommandArgs.includes('-h')) ||
        (subcommand === 'man' && subcommandArgs.includes('-h')) ||
        (subcommand === 'manual' && subcommandArgs.includes('-h')) ||
        ((subcommand === 'create' || subcommand === 'new') && subcommandArgs.includes('-h')) ||
        (subcommand === 'install' &&
            (subcommandArgs.includes('--help') || subcommandArgs.includes('-h'))) ||
        (subcommand === 'doctor' &&
            (subcommandArgs.includes('--help') || subcommandArgs.includes('-h'))) ||
        (subcommand === 'enable' &&
            (subcommandArgs.includes('--help') || subcommandArgs.includes('-h'))) ||
        (subcommand === 'disable' &&
            (subcommandArgs.includes('--help') || subcommandArgs.includes('-h'))) ||
        (subcommand === 'uninstall' &&
            (subcommandArgs.includes('--help') || subcommandArgs.includes('-h'))) ||
        (subcommand === 'update' &&
            (subcommandArgs.includes('--help') || subcommandArgs.includes('-h')));
    if (!shouldSkipRtwsSetup) {
        // Load runtime workspace env files into process.env once, in the main entry.
        // Precedence: `.env` then `.env.local` (later overwrites earlier), and both
        // overwrite any existing process.env values.
        (0, dotenv_1.loadRtwsDotenv)({ cwd: (0, rtws_1.domindsRtwsRootAbs)() });
        configureEnvProxySupport();
    }
    const shouldLoadApps = subcommand !== 'webui' &&
        subcommand !== 'cert' &&
        subcommand !== 'create' &&
        subcommand !== 'new' &&
        subcommand !== 'install' &&
        subcommand !== 'doctor' &&
        subcommand !== 'enable' &&
        subcommand !== 'disable' &&
        subcommand !== 'uninstall' &&
        subcommand !== 'update';
    if (!shouldSkipRtwsSetup && shouldLoadApps) {
        try {
            // Register toolset proxies so Team.load() can validate toolset bindings (read/man/manual included).
            await (0, runtime_1.registerEnabledAppsToolProxies)({ rtwsRootAbs: (0, rtws_1.domindsRtwsRootAbs)() });
            // Start apps-host only for interactive runtime commands (do not auto-start app frontends for read/man/manual).
            const shouldStartAppsHost = subcommand === 'tui' || subcommand === 'run';
            if (shouldStartAppsHost) {
                await (0, runtime_1.initAppsRuntime)({
                    rtwsRootAbs: (0, rtws_1.domindsRtwsRootAbs)(),
                    kernel: { scheme: 'http', host: '127.0.0.1', port: 0 },
                });
            }
        }
        catch (err) {
            console.error('Error: failed to load enabled apps:', err instanceof Error ? err.message : String(err));
            process.exit(1);
        }
    }
    // Route to appropriate subcommand
    switch (subcommand) {
        case 'webui':
            await runSubcommand('webui', subcommandArgs);
            break;
        case 'tui':
        case 'run':
            await runSubcommand('tui', subcommandArgs);
            break;
        case 'read':
            await runSubcommand('read', subcommandArgs);
            break;
        case 'man':
            await runSubcommand('manual', subcommandArgs);
            break;
        case 'manual':
            await runSubcommand('manual', subcommandArgs);
            break;
        case 'validate_team_def':
            await runSubcommand('validate_team_def', subcommandArgs);
            break;
        case 'cert':
            await runSubcommand('cert', subcommandArgs);
            break;
        case 'create':
        case 'new':
            await runSubcommand('create', subcommandArgs);
            break;
        case 'install':
            await runSubcommand('install', subcommandArgs);
            break;
        case 'doctor':
            await runSubcommand('doctor', subcommandArgs);
            break;
        case 'enable':
            await runSubcommand('enable', subcommandArgs);
            break;
        case 'disable':
            await runSubcommand('disable', subcommandArgs);
            break;
        case 'uninstall':
            await runSubcommand('uninstall', subcommandArgs);
            break;
        case 'update':
            await runSubcommand('update', subcommandArgs);
            break;
        default:
            console.error(`Error: Unknown subcommand '${subcommand}'`);
            console.error(`Run 'dominds help' for usage information.`);
            process.exit(1);
    }
}
async function runSubcommand(subcommand, args) {
    try {
        (0, process_title_1.setRtwsProcessTitle)();
        if (subcommand === 'webui') {
            await (0, webui_1.main)(args);
        }
        else if (subcommand === 'tui') {
            await (0, tui_1.main)(args);
        }
        else if (subcommand === 'read') {
            await (0, read_1.main)(args);
        }
        else if (subcommand === 'manual') {
            await (0, manual_1.main)(args);
        }
        else if (subcommand === 'validate_team_def') {
            await (0, validate_team_def_1.main)(args);
        }
        else if (subcommand === 'cert') {
            await (0, cert_1.main)(args);
        }
        else if (subcommand === 'create') {
            await (0, create_1.main)(args);
        }
        else if (subcommand === 'install') {
            await (0, install_1.main)(args);
        }
        else if (subcommand === 'doctor') {
            await (0, doctor_1.main)(args);
        }
        else if (subcommand === 'enable') {
            await (0, enable_1.main)(args);
        }
        else if (subcommand === 'disable') {
            await (0, disable_1.main)(args);
        }
        else if (subcommand === 'uninstall') {
            await (0, uninstall_1.main)(args);
        }
        else if (subcommand === 'update') {
            await (0, update_1.main)(args);
        }
        else {
            console.error(`Error: Subcommand '${subcommand}' not implemented`);
            process.exit(1);
        }
    }
    catch (err) {
        console.error(`Failed to execute subcommand '${subcommand}': ${err instanceof Error ? err.message : String(err)}`);
        process.exit(1);
    }
}
if (require.main === module) {
    main().catch((err) => {
        console.error('Unhandled error:', err);
        process.exit(1);
    });
}
