"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 });
exports.listWorkflows = listWorkflows;
exports.invokeWorkflow = invokeWorkflow;
exports.getWorkflowStatus = getWorkflowStatus;
exports.getWorkflowResult = getWorkflowResult;
exports.terminateWorkflow = terminateWorkflow;
const picocolors_1 = __importDefault(require("picocolors"));
const client_1 = require("../client");
const format_1 = require("../format");
const COLUMNS = [
    { key: 'workflow_type', label: 'Type', width: 24 },
    { key: 'task_queue', label: 'Queue', width: 16 },
    { key: 'tier', label: 'Tier', width: 12 },
    { key: 'active', label: 'Active', width: 8, format: (v) => v ? picocolors_1.default.green('yes') : picocolors_1.default.dim('no') },
    { key: 'invocable', label: 'Invocable', width: 10, format: (v) => v ? 'yes' : picocolors_1.default.dim('no') },
];
async function listWorkflows(opts) {
    const params = new URLSearchParams();
    if (opts.includeSystem)
        params.set('include_system', 'true');
    const data = await (0, client_1.apiFetch)(`/workflows/discovered?${params}`);
    (0, format_1.output)(data, data.workflows || [], COLUMNS, opts, 'workflow_type');
}
async function invokeWorkflow(type, opts) {
    const inputData = opts.data ? JSON.parse(opts.data) : {};
    const data = await (0, client_1.apiFetch)(`/workflows/${type}/invoke`, {
        method: 'POST',
        body: JSON.stringify({ data: inputData }),
    });
    if (opts.json) {
        console.log(JSON.stringify(data, null, 2));
        return;
    }
    console.log(`\n  ${picocolors_1.default.green('✓')} Started ${picocolors_1.default.bold(type)} → ${picocolors_1.default.dim(data.workflowId)}\n`);
}
async function getWorkflowStatus(id, opts) {
    const data = await (0, client_1.apiFetch)(`/workflows/status/${id}`);
    if (opts.json) {
        console.log(JSON.stringify(data, null, 2));
        return;
    }
    const status = data.status === 0 ? picocolors_1.default.green('completed') : picocolors_1.default.blue('running');
    console.log(`\n  ${data.workflowId}  ${status}\n`);
}
async function getWorkflowResult(id, opts) {
    const { server, token } = await (await Promise.resolve().then(() => __importStar(require('../auth')))).resolveAuth();
    const res = await fetch(`${server}/api/workflows/${id}/result`, {
        headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },
    });
    const data = await res.json();
    if (opts.json) {
        console.log(JSON.stringify(data, null, 2));
        return;
    }
    if (res.status === 202) {
        console.log(`\n  ${picocolors_1.default.blue('⏳')} Still running: ${id}\n`);
    }
    else {
        console.log(`\n  ${picocolors_1.default.green('✓')} Result for ${picocolors_1.default.dim(id)}:`);
        console.log(JSON.stringify(data.result?.data ?? data.result ?? data, null, 2));
        console.log();
    }
}
async function terminateWorkflow(id) {
    await (0, client_1.apiFetch)(`/workflows/terminate/${id}`, { method: 'POST' });
    console.log(`\n  ${picocolors_1.default.green('✓')} Terminated ${picocolors_1.default.dim(id)}\n`);
}
