#!/usr/bin/env node
"use strict";
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;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
// Suppress internal logger output in CLI mode
process.env.LOG_LEVEL = process.env.LOG_LEVEL || 'error';
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
require("dotenv/config");
const commander_1 = require("commander");
const picocolors_1 = __importDefault(require("picocolors"));
const compile_1 = require("../lib/cli/compile");
const init_1 = require("../lib/cli/init");
const auth_1 = require("../lib/cli/auth");
const status_1 = require("../lib/cli/commands/status");
const esc = __importStar(require("../lib/cli/commands/escalations"));
const wf = __importStar(require("../lib/cli/commands/workflows"));
const pip = __importStar(require("../lib/cli/commands/pipelines"));
const kb = __importStar(require("../lib/cli/commands/knowledge"));
const mcp = __importStar(require("../lib/cli/commands/mcp"));
const usr = __importStar(require("../lib/cli/commands/users"));
const streams = __importStar(require("../lib/cli/commands/streams"));
const pkg = require('../package.json');
const envPath = path.resolve(process.cwd(), '.env');
const envLoaded = fs.existsSync(envPath);
// ── Error handler ────────────────────────────────────────────────────────
function handleError(err) {
    const msg = err.message || String(err);
    console.error(`\n  ${picocolors_1.default.red('✗')} ${msg}\n`);
    process.exit(1);
}
function wrap(fn) {
    return (...args) => fn(...args).catch(handleError);
}
// ── Program ──────────────────────────────────────────────────────────────
commander_1.program
    .name('ltc')
    .description('Long Tail CLI — workflows, escalations, knowledge, and more')
    .version(pkg.version)
    .hook('preAction', (thisCommand) => {
    const cmd = thisCommand.args?.[0];
    // Skip banner for quiet/json modes and version
    if (process.argv.includes('-q') || process.argv.includes('--quiet') || process.argv.includes('--json'))
        return;
    if (cmd === '--version' || cmd === '-V')
        return;
    console.log();
    console.log(`  ${picocolors_1.default.bold('ltc')} ${picocolors_1.default.dim(`v${pkg.version}`)}`);
    if (envLoaded)
        console.log(`  ${picocolors_1.default.dim('.env loaded')}`);
});
// ── Auth ─────────────────────────────────────────────────────────────────
commander_1.program
    .command('login')
    .description('Authenticate with a Long Tail instance')
    .option('-s, --server <url>', 'Server URL')
    .option('-u, --username <name>', 'Username')
    .option('-p, --password <pass>', 'Password')
    .action(wrap(async (opts) => (0, auth_1.login)(opts)));
commander_1.program
    .command('logout')
    .description('Clear stored credentials')
    .action(() => (0, auth_1.logout)());
commander_1.program
    .command('status')
    .description('Show instance health and summary counts')
    .action(wrap(status_1.statusCommand));
// ── Compile ──────────────────────────────────────────────────────────────
commander_1.program
    .command('compile [target]')
    .description('Compile durable TypeScript workflows to YAML DAGs')
    .option('--dry-run', 'Show discovered workflows without compiling')
    .option('-o, --output <dir>', 'Output directory (default: adjacent to source)')
    .option('--model <model>', 'LLM model to use')
    .option('--function <name>', 'Workflow function name (auto-detected if omitted)')
    .option('-q, --quiet', 'Minimal output (exit codes only)')
    .action(compile_1.compileCommand);
commander_1.program
    .command('init')
    .description('Create a .env file with API key template')
    .action(init_1.initCommand);
// ── Escalations ──────────────────────────────────────────────────────────
const escCmd = commander_1.program.command('escalations').alias('esc').description('Manage escalations');
escCmd.command('list')
    .option('--status <status>', 'Filter by status (pending, resolved, cancelled)')
    .option('--role <role>', 'Filter by role')
    .option('--limit <n>', 'Max results')
    .option('--json', 'JSON output')
    .option('-q, --quiet', 'IDs only')
    .action(wrap(esc.listEscalations));
escCmd.command('get <id>')
    .option('--json', 'JSON output')
    .action(wrap(esc.getEscalation));
escCmd.command('claim <id>')
    .option('--duration <minutes>', 'Claim duration in minutes')
    .action(wrap(esc.claimEscalation));
escCmd.command('release <id>')
    .action(wrap(esc.releaseEscalation));
escCmd.command('resolve <id>')
    .requiredOption('--data <json>', 'Resolver payload (JSON string)')
    .action(wrap(esc.resolveEscalation));
// ── Workflows ────────────────────────────────────────────────────────────
const wfCmd = commander_1.program.command('workflows').alias('wf').description('Manage durable workflows');
wfCmd.command('list')
    .option('--include-system', 'Include system workflows')
    .option('--json', 'JSON output')
    .option('-q, --quiet', 'IDs only')
    .action(wrap(wf.listWorkflows));
wfCmd.command('invoke <type>')
    .option('--data <json>', 'Input data (JSON string)')
    .option('--json', 'JSON output')
    .action(wrap(wf.invokeWorkflow));
wfCmd.command('status <id>')
    .option('--json', 'JSON output')
    .action(wrap(wf.getWorkflowStatus));
wfCmd.command('result <id>')
    .option('--json', 'JSON output')
    .action(wrap(wf.getWorkflowResult));
wfCmd.command('terminate <id>')
    .action(wrap(wf.terminateWorkflow));
// ── Pipelines (YAML Workflows) ──────────────────────────────────────────
const pipCmd = commander_1.program.command('pipelines').alias('pip').description('Manage YAML pipeline tools');
pipCmd.command('list')
    .option('--status <status>', 'Filter by status (active, draft, deployed, archived)')
    .option('--limit <n>', 'Max results')
    .option('--json', 'JSON output')
    .option('-q, --quiet', 'IDs only')
    .action(wrap(pip.listPipelines));
pipCmd.command('get <id>')
    .option('--json', 'JSON output')
    .action(wrap(pip.getPipeline));
pipCmd.command('deploy <id>')
    .action(wrap(pip.deployPipeline));
pipCmd.command('invoke <id>')
    .option('--data <json>', 'Input data (JSON string)')
    .option('--sync', 'Wait for result')
    .option('--json', 'JSON output')
    .action(wrap(pip.invokePipeline));
pipCmd.command('archive <id>')
    .action(wrap(pip.archivePipeline));
// ── Knowledge ────────────────────────────────────────────────────────────
const kbCmd = commander_1.program.command('knowledge').alias('kb').description('Manage knowledge store');
kbCmd.command('domains')
    .option('--json', 'JSON output')
    .option('-q, --quiet', 'IDs only')
    .action(wrap(kb.listDomains));
kbCmd.command('list <domain>')
    .option('--search <term>', 'Search by key or tag')
    .option('--limit <n>', 'Max results')
    .option('--json', 'JSON output')
    .option('-q, --quiet', 'Keys only')
    .action(wrap(kb.listEntries));
kbCmd.command('get <domain> <key>')
    .option('--json', 'JSON output')
    .action(wrap(kb.getEntry));
kbCmd.command('set <domain> <key> <path> <value>')
    .option('--json', 'JSON output')
    .description('Set a value at a dot-path (e.g., ltc kb set research screenshots google.holiday "Mother\'s Day")')
    .action(wrap(kb.setField));
kbCmd.command('remove <domain> <key> <path>')
    .description('Remove a field at a dot-path')
    .action(wrap(kb.removeField));
kbCmd.command('delete <domain> <key>')
    .description('Delete an entire entry')
    .action(wrap(kb.deleteEntry));
// ── MCP ──────────────────────────────────────────────────────────────────
const mcpCmd = commander_1.program.command('mcp').description('MCP server and tool management');
mcpCmd.command('servers')
    .option('--json', 'JSON output')
    .option('-q, --quiet', 'IDs only')
    .action(wrap(mcp.listServers));
mcpCmd.command('tools <serverId>')
    .option('--json', 'JSON output')
    .option('-q, --quiet', 'Names only')
    .action(wrap(mcp.listTools));
// ── Users ────────────────────────────────────────────────────────────────
const usrCmd = commander_1.program.command('users').description('User management (admin)');
usrCmd.command('list')
    .option('--json', 'JSON output')
    .option('-q, --quiet', 'IDs only')
    .action(wrap(usr.listUsers));
usrCmd.command('get <id>')
    .option('--json', 'JSON output')
    .action(wrap(usr.getUser));
// ── Streams ─────────────────────────────────────────────────────────────
const streamsCmd = commander_1.program.command('streams').description('Browse stream messages (admin)');
streamsCmd.command('list')
    .requiredOption('-n, --namespace <ns>', 'Schema namespace (e.g. durable)')
    .requiredOption('-s, --source <source>', 'Stream type (engine or worker)')
    .option('--status <status>', 'Filter by status (pending, claimed, processed, dead_lettered)')
    .option('--stream <name>', 'Filter by stream name (partial match)')
    .option('--type <type>', 'Filter by message type (worker only)')
    .option('--limit <n>', 'Max results (default 25)')
    .option('--offset <n>', 'Pagination offset')
    .option('--sort <col>', 'Sort column (created_at, stream_name, priority, id)')
    .option('--order <dir>', 'Sort direction (asc, desc)')
    .option('--json', 'JSON output')
    .option('-q, --quiet', 'IDs only')
    .action(wrap(streams.listMessages));
// ── Parse ────────────────────────────────────────────────────────────────
commander_1.program.parse();
