var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
import { Resolver, Mutation, Arg, Ctx, ObjectType, Field, PubSub, PubSubEngine } from 'type-graphql';
import { LogError, LogStatus } from '@memberjunction/core';
import { ResolverBase } from '../generic/ResolverBase.js';
import { TaskOrchestrator } from '../services/TaskOrchestrator.js';
let TaskExecutionResultType = class TaskExecutionResultType {
    taskId;
    success;
    output;
    error;
};
__decorate([
    Field(),
    __metadata("design:type", String)
], TaskExecutionResultType.prototype, "taskId", void 0);
__decorate([
    Field(),
    __metadata("design:type", Boolean)
], TaskExecutionResultType.prototype, "success", void 0);
__decorate([
    Field({ nullable: true }),
    __metadata("design:type", String)
], TaskExecutionResultType.prototype, "output", void 0);
__decorate([
    Field({ nullable: true }),
    __metadata("design:type", String)
], TaskExecutionResultType.prototype, "error", void 0);
TaskExecutionResultType = __decorate([
    ObjectType()
], TaskExecutionResultType);
export { TaskExecutionResultType };
let ExecuteTaskGraphResult = class ExecuteTaskGraphResult {
    success;
    errorMessage;
    results;
};
__decorate([
    Field(),
    __metadata("design:type", Boolean)
], ExecuteTaskGraphResult.prototype, "success", void 0);
__decorate([
    Field({ nullable: true }),
    __metadata("design:type", String)
], ExecuteTaskGraphResult.prototype, "errorMessage", void 0);
__decorate([
    Field(() => [TaskExecutionResultType]),
    __metadata("design:type", Array)
], ExecuteTaskGraphResult.prototype, "results", void 0);
ExecuteTaskGraphResult = __decorate([
    ObjectType()
], ExecuteTaskGraphResult);
export { ExecuteTaskGraphResult };
let TaskOrchestrationResolver = class TaskOrchestrationResolver extends ResolverBase {
    async ExecuteTaskGraph(taskGraphJson, conversationDetailId, environmentId, sessionId, pubSub, { userPayload }, createNotifications) {
        try {
            LogStatus(`=== EXECUTING TASK GRAPH FOR CONVERSATION: ${conversationDetailId} ===`);
            const taskGraph = JSON.parse(taskGraphJson);
            if (!taskGraph.workflowName || !taskGraph.tasks || taskGraph.tasks.length === 0) {
                throw new Error('Invalid task graph: must have workflowName and at least one task');
            }
            const currentUser = this.GetUserFromPayload(userPayload);
            if (!currentUser) {
                throw new Error('Unable to determine current user');
            }
            LogStatus(`Workflow: ${taskGraph.workflowName} (${taskGraph.tasks.length} tasks)`);
            if (taskGraph.reasoning) {
                LogStatus(`Reasoning: ${taskGraph.reasoning}`);
            }
            const orchestrator = new TaskOrchestrator(currentUser, pubSub, sessionId, userPayload, createNotifications || false, conversationDetailId);
            const { parentTaskId, taskIdMap } = await orchestrator.createTasksFromGraph(taskGraph, conversationDetailId, environmentId);
            LogStatus(`Created parent task ${parentTaskId} with ${taskIdMap.size} child tasks`);
            const results = await orchestrator.executeTasksForParent(parentTaskId);
            const successCount = results.filter(r => r.success).length;
            LogStatus(`Completed ${successCount} of ${results.length} tasks successfully`);
            for (const result of results) {
                if (result.success) {
                    LogStatus(`✅ Task ${result.taskId} completed successfully`);
                }
                else {
                    LogError(`❌ Task ${result.taskId} failed: ${result.error}`);
                }
            }
            const graphqlResults = results.map(r => ({
                taskId: r.taskId,
                success: r.success,
                output: r.output ? JSON.stringify(r.output) : undefined,
                error: r.error
            }));
            LogStatus(`=== TASK GRAPH EXECUTION COMPLETE ===`);
            const result = {
                success: true,
                results: graphqlResults
            };
            LogStatus(`Returning ExecuteTaskGraph result: ${JSON.stringify({
                success: result.success,
                resultsCount: result.results.length,
                firstResult: result.results[0]
            })}`);
            return result;
        }
        catch (error) {
            LogError(`Task graph execution failed:`, undefined, error);
            return {
                success: false,
                errorMessage: error.message || 'Unknown error occurred',
                results: []
            };
        }
    }
};
__decorate([
    Mutation(() => ExecuteTaskGraphResult),
    __param(0, Arg('taskGraphJson')),
    __param(1, Arg('conversationDetailId')),
    __param(2, Arg('environmentId')),
    __param(3, Arg('sessionId')),
    __param(4, PubSub()),
    __param(5, Ctx()),
    __param(6, Arg('createNotifications', { nullable: true })),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String, String, String, PubSubEngine, Object, Boolean]),
    __metadata("design:returntype", Promise)
], TaskOrchestrationResolver.prototype, "ExecuteTaskGraph", null);
TaskOrchestrationResolver = __decorate([
    Resolver()
], TaskOrchestrationResolver);
export { TaskOrchestrationResolver };
//# sourceMappingURL=TaskResolver.js.map