"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;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.createClient = createClient;
const tasksApi = __importStar(require("../api/tasks"));
const escalationsApi = __importStar(require("../api/escalations"));
const workflowsApi = __importStar(require("../api/workflows"));
const yamlWorkflowsApi = __importStar(require("../api/yaml-workflows"));
const usersApi = __importStar(require("../api/users"));
const rolesApi = __importStar(require("../api/roles"));
const authApi = __importStar(require("../api/auth"));
const mcpApi = __importStar(require("../api/mcp"));
const pipelinesApi = __importStar(require("../api/pipelines"));
const insightApi = __importStar(require("../api/insight"));
const settingsApi = __importStar(require("../api/settings"));
const exportsApi = __importStar(require("../api/exports"));
const controlplaneApi = __importStar(require("../api/controlplane"));
const botAccountsApi = __importStar(require("../api/bot-accounts"));
const workflowSetsApi = __importStar(require("../api/workflow-sets"));
const dbaApi = __importStar(require("../api/dba"));
const namespacesApi = __importStar(require("../api/namespaces"));
const maintenanceApi = __importStar(require("../api/maintenance"));
const filesApi = __importStar(require("../api/files"));
const knowledgeApi = __importStar(require("../api/knowledge"));
const agentsApi = __importStar(require("../api/agents"));
const agentSubsApi = __importStar(require("../api/agent-subscriptions"));
const events_1 = require("../lib/events");
const callback_1 = require("../lib/events/callback");
/** Bind auth context to a function that expects it as the last argument. */
function bindAuth(fn, defaultAuth) {
    return (input, auth) => {
        const resolvedAuth = auth ?? defaultAuth;
        if (!resolvedAuth) {
            return Promise.resolve({ status: 401, error: 'Auth context required' });
        }
        return fn(input, resolvedAuth);
    };
}
/** Bind optional auth context — passes undefined if not available. */
function bindOptionalAuth(fn, defaultAuth) {
    return (input, auth) => fn(input, auth ?? defaultAuth);
}
/**
 * Create a Long Tail SDK client for direct in-process API calls.
 *
 * All operations go through the same API layer as HTTP routes —
 * same validation, same RBAC, same event publishing — without
 * HTTP transport overhead.
 *
 * ```typescript
 * import { createClient } from '@hotmeshio/long-tail/sdk';
 *
 * const lt = createClient({ auth: { userId: 'system' } });
 *
 * const result = await lt.escalations.claim({ id: 'esc_123', durationMinutes: 30 });
 * // { status: 200, data: { escalation: {...}, isExtension: false } }
 *
 * lt.events.on('escalation.claimed', (event) => {
 *   console.log('claimed:', event.escalationId);
 * });
 * ```
 */
function createClient(options = {}) {
    const auth = options.auth;
    // Get or create the CallbackEventAdapter singleton
    let callbackAdapter = events_1.eventRegistry.getAdapter(callback_1.CallbackEventAdapter);
    if (!callbackAdapter) {
        callbackAdapter = new callback_1.CallbackEventAdapter();
        events_1.eventRegistry.register(callbackAdapter);
        callbackAdapter.connect();
    }
    return {
        // ── Tasks ──────────────────────────────────────────────────────────────
        tasks: {
            create: bindAuth(tasksApi.createTask, auth),
            list: tasksApi.listTasks,
            get: tasksApi.getTask,
            listProcesses: tasksApi.listProcesses,
            getProcess: tasksApi.getProcess,
            getProcessStats: tasksApi.getProcessStats,
        },
        // ── Escalations ────────────────────────────────────────────────────────
        escalations: {
            create: bindAuth(escalationsApi.createEscalation, auth),
            list: bindAuth(escalationsApi.listEscalations, auth),
            listAvailable: bindAuth(escalationsApi.listAvailableEscalations, auth),
            listTypes: escalationsApi.listDistinctTypes,
            getStats: bindAuth(escalationsApi.getEscalationStats, auth),
            get: bindAuth(escalationsApi.getEscalation, auth),
            getByWorkflowId: escalationsApi.getEscalationsByWorkflowId,
            escalate: bindAuth(escalationsApi.escalateToRole, auth),
            claim: bindAuth(escalationsApi.claimEscalation, auth),
            release: bindAuth(escalationsApi.releaseEscalation, auth),
            resolve: bindAuth(escalationsApi.resolveEscalation, auth),
            releaseExpired: escalationsApi.releaseExpiredClaims,
            updatePriority: bindAuth(escalationsApi.updatePriority, auth),
            bulkClaim: bindAuth(escalationsApi.bulkClaim, auth),
            bulkAssign: bindAuth(escalationsApi.bulkAssign, auth),
            bulkEscalate: bindAuth(escalationsApi.bulkEscalate, auth),
            bulkTriage: bindAuth(escalationsApi.bulkTriage, auth),
        },
        // ── Workflows ──────────────────────────────────────────────────────────
        workflows: {
            invoke: bindAuth(workflowsApi.invokeWorkflow, auth),
            getStatus: workflowsApi.getWorkflowStatus,
            getResult: workflowsApi.getWorkflowResult,
            terminate: workflowsApi.terminateWorkflow,
            export: workflowsApi.exportWorkflow,
            listWorkers: workflowsApi.listWorkers,
            listDiscovered: workflowsApi.listDiscoveredWorkflows,
            getCronStatus: workflowsApi.getCronStatus,
            listConfigs: workflowsApi.listWorkflowConfigs,
            getConfig: workflowsApi.getWorkflowConfig,
            upsertConfig: workflowsApi.upsertWorkflowConfig,
            deleteConfig: workflowsApi.deleteWorkflowConfig,
        },
        // ── YAML Workflows ─────────────────────────────────────────────────────
        yamlWorkflows: {
            list: yamlWorkflowsApi.listYamlWorkflows,
            create: yamlWorkflowsApi.createYamlWorkflow,
            createDirect: yamlWorkflowsApi.createYamlWorkflowDirect,
            getAppIds: yamlWorkflowsApi.getAppIds,
            get: yamlWorkflowsApi.getYamlWorkflow,
            update: yamlWorkflowsApi.updateYamlWorkflow,
            regenerate: yamlWorkflowsApi.regenerateYamlWorkflow,
            delete: yamlWorkflowsApi.deleteYamlWorkflow,
            deploy: yamlWorkflowsApi.deployYamlWorkflow,
            activate: yamlWorkflowsApi.activateYamlWorkflow,
            invoke: bindOptionalAuth(yamlWorkflowsApi.invokeYamlWorkflow, auth),
            archive: yamlWorkflowsApi.archiveYamlWorkflow,
            getVersionHistory: yamlWorkflowsApi.getVersionHistory,
            getVersionSnapshot: yamlWorkflowsApi.getVersionSnapshot,
            getYamlContent: yamlWorkflowsApi.getYamlContent,
            setCronSchedule: yamlWorkflowsApi.setCronSchedule,
            clearCronSchedule: yamlWorkflowsApi.clearCronSchedule,
            getCronStatus: yamlWorkflowsApi.getCronStatus,
        },
        // ── Users ──────────────────────────────────────────────────────────────
        users: {
            list: usersApi.listUsers,
            get: usersApi.getUser,
            create: usersApi.createUser,
            update: usersApi.updateUser,
            delete: usersApi.deleteUser,
            getRoles: usersApi.getUserRoles,
            addRole: usersApi.addUserRole,
            removeRole: usersApi.removeUserRole,
        },
        // ── Roles ──────────────────────────────────────────────────────────────
        roles: {
            list: rolesApi.listRoles,
            listWithDetails: rolesApi.listRolesWithDetails,
            create: rolesApi.createRole,
            delete: rolesApi.deleteRole,
            getEscalationChains: rolesApi.getEscalationChains,
            addEscalationChain: rolesApi.addEscalationChain,
            removeEscalationChain: rolesApi.removeEscalationChain,
            getEscalationTargets: rolesApi.getEscalationTargets,
            replaceEscalationTargets: rolesApi.replaceEscalationTargets,
        },
        // ── Auth ───────────────────────────────────────────────────────────────
        auth: {
            login: authApi.login,
        },
        // ── MCP ────────────────────────────────────────────────────────────────
        mcp: {
            listServers: mcpApi.listMcpServers,
            createServer: mcpApi.createMcpServer,
            testConnection: mcpApi.testConnection,
            getServer: mcpApi.getMcpServer,
            updateServer: mcpApi.updateMcpServer,
            deleteServer: mcpApi.deleteMcpServer,
            connectServer: mcpApi.connectMcpServer,
            disconnectServer: mcpApi.disconnectMcpServer,
            getCredentialStatus: bindAuth(mcpApi.getCredentialStatus, auth),
            listTools: mcpApi.listMcpServerTools,
            callTool: bindOptionalAuth(mcpApi.callMcpTool, auth),
        },
        // ── Pipelines ──────────────────────────────────────────────────────────
        pipelines: {
            listEntities: pipelinesApi.listEntities,
            listJobs: pipelinesApi.listJobs,
            getExecution: pipelinesApi.getJobExecution,
            interrupt: pipelinesApi.interruptJob,
        },
        /** @deprecated Use `pipelines` */
        mcpRuns: {
            listEntities: pipelinesApi.listEntities,
            listJobs: pipelinesApi.listJobs,
            getExecution: pipelinesApi.getJobExecution,
        },
        // ── Insight ────────────────────────────────────────────────────────────
        insight: {
            mcpQuery: bindOptionalAuth(insightApi.mcpQuery, auth),
            buildWorkflow: bindOptionalAuth(insightApi.buildWorkflow, auth),
            refineWorkflow: bindOptionalAuth(insightApi.refineWorkflow, auth),
            describeWorkflow: insightApi.describeWorkflow,
        },
        // ── Settings ───────────────────────────────────────────────────────────
        settings: {
            get: settingsApi.getSettings,
        },
        // ── Exports ────────────────────────────────────────────────────────────
        exports: {
            listJobs: exportsApi.listJobs,
            exportState: exportsApi.exportWorkflowState,
            exportExecution: exportsApi.exportWorkflowExecution,
            getStatus: exportsApi.getWorkflowStatus,
            getState: exportsApi.getWorkflowState,
        },
        // ── Control Plane ──────────────────────────────────────────────────────
        controlplane: {
            listApps: controlplaneApi.listApps,
            rollCall: controlplaneApi.rollCall,
            throttle: controlplaneApi.applyThrottle,
            getStreamStats: controlplaneApi.getStreamStats,
            listStreamMessages: controlplaneApi.listStreamMessages,
            subscribe: controlplaneApi.subscribeMesh,
        },
        // ── Bot Accounts ───────────────────────────────────────────────────────
        botAccounts: {
            list: botAccountsApi.listBots,
            get: botAccountsApi.getBot,
            create: bindOptionalAuth(botAccountsApi.createBot, auth),
            update: botAccountsApi.updateBot,
            delete: botAccountsApi.deleteBot,
            getRoles: botAccountsApi.getBotRoles,
            addRole: botAccountsApi.addBotRole,
            removeRole: botAccountsApi.removeBotRole,
            listKeys: botAccountsApi.listBotKeys,
            createKey: botAccountsApi.createBotKey,
            revokeKey: botAccountsApi.revokeBotKey,
        },
        // ── Workflow Sets ──────────────────────────────────────────────────────
        workflowSets: {
            create: bindOptionalAuth(workflowSetsApi.createWorkflowSet, auth),
            list: workflowSetsApi.listWorkflowSets,
            get: workflowSetsApi.getWorkflowSet,
            updatePlan: workflowSetsApi.updateWorkflowSetPlanApi,
            build: workflowSetsApi.buildWorkflowSet,
            deploy: workflowSetsApi.deployWorkflowSet,
        },
        // ── DBA ────────────────────────────────────────────────────────────────
        dba: {
            prune: dbaApi.prune,
            deploy: dbaApi.deploy,
        },
        // ── Namespaces ─────────────────────────────────────────────────────────
        namespaces: {
            list: namespacesApi.listNamespaces,
            register: namespacesApi.registerNamespace,
        },
        // ── Maintenance ────────────────────────────────────────────────────────
        maintenance: {
            getConfig: maintenanceApi.getMaintenanceConfig,
            updateConfig: maintenanceApi.updateMaintenanceConfig,
        },
        // ── Files ──────────────────────────────────────────────────────────────
        files: {
            browse: filesApi.browseFiles,
            getMetadata: filesApi.getFileMetadata,
            delete: filesApi.deleteFile,
            generateSignedUrl: filesApi.generateSignedUrl,
        },
        // ── Knowledge ─────────────────────────────────────────────────────────
        knowledge: {
            listDomains: knowledgeApi.listDomains,
            listEntries: knowledgeApi.listEntries,
            getEntry: knowledgeApi.getEntry,
            storeEntry: knowledgeApi.storeEntry,
            setField: knowledgeApi.setField,
            removeField: knowledgeApi.removeField,
            deleteEntry: knowledgeApi.deleteEntry,
        },
        // ── Agents ──────────────────────────────────────────────────────────────
        agents: {
            list: (input) => agentsApi.listAgents(input ?? {}),
            get: agentsApi.getAgent,
            create: (input) => agentsApi.createAgent(input, auth),
            update: agentsApi.updateAgent,
            delete: agentsApi.deleteAgent,
            listSubscriptions: agentSubsApi.listSubscriptions,
            createSubscription: agentSubsApi.createSubscription,
            updateSubscription: agentSubsApi.updateSubscription,
            deleteSubscription: agentSubsApi.deleteSubscription,
        },
        // ── Events ─────────────────────────────────────────────────────────────
        events: {
            /**
             * Subscribe to Long Tail events.
             *
             * Supports exact types (`'task.created'`), category wildcards (`'task.*'`),
             * and global wildcard (`'*'`).
             *
             * Returns an unsubscribe function.
             *
             * ```typescript
             * const unsub = lt.events.on('escalation.claimed', (event) => {
             *   console.log('claimed:', event.escalationId);
             * });
             * // Later: unsub();
             * ```
             */
            on: (pattern, callback) => {
                return callbackAdapter.on(pattern, callback);
            },
        },
    };
}
