import { promises as fs } from 'fs';
import path from 'path';
export class OrchestrationStore {
    basePath;
    constructor(basePath = '.atlas/orchestration') {
        this.basePath = basePath;
    }
    async ensureDirectory(dir) {
        await fs.mkdir(dir, { recursive: true });
    }
    // Workflow persistence
    async saveWorkflow(workflow) {
        const dir = path.join(this.basePath, 'workflows');
        await this.ensureDirectory(dir);
        const filePath = path.join(dir, `${workflow.id}.json`);
        await fs.writeFile(filePath, JSON.stringify(workflow, null, 2));
    }
    async loadWorkflow(workflowId) {
        const filePath = path.join(this.basePath, 'workflows', `${workflowId}.json`);
        try {
            const content = await fs.readFile(filePath, 'utf-8');
            return JSON.parse(content);
        }
        catch (error) {
            return null;
        }
    }
    async listWorkflows() {
        const dir = path.join(this.basePath, 'workflows');
        try {
            await this.ensureDirectory(dir);
            const files = await fs.readdir(dir);
            const workflows = [];
            for (const file of files) {
                if (file.endsWith('.json')) {
                    const content = await fs.readFile(path.join(dir, file), 'utf-8');
                    workflows.push(JSON.parse(content));
                }
            }
            return workflows;
        }
        catch (error) {
            return [];
        }
    }
    async deleteWorkflow(workflowId) {
        const filePath = path.join(this.basePath, 'workflows', `${workflowId}.json`);
        try {
            await fs.unlink(filePath);
        }
        catch (error) {
            // Ignore if file doesn't exist
        }
    }
    // Execution persistence
    async saveExecution(execution) {
        const dir = path.join(this.basePath, 'executions', execution.workflowId);
        await this.ensureDirectory(dir);
        const filePath = path.join(dir, `${execution.id}.json`);
        await fs.writeFile(filePath, JSON.stringify(execution, null, 2));
    }
    async loadExecution(executionId, workflowId) {
        if (workflowId) {
            const filePath = path.join(this.basePath, 'executions', workflowId, `${executionId}.json`);
            try {
                const content = await fs.readFile(filePath, 'utf-8');
                return JSON.parse(content);
            }
            catch (error) {
                return null;
            }
        }
        // Search all workflow directories
        const executionsDir = path.join(this.basePath, 'executions');
        try {
            const workflowDirs = await fs.readdir(executionsDir);
            for (const dir of workflowDirs) {
                const filePath = path.join(executionsDir, dir, `${executionId}.json`);
                try {
                    const content = await fs.readFile(filePath, 'utf-8');
                    return JSON.parse(content);
                }
                catch (error) {
                    // Continue searching
                }
            }
        }
        catch (error) {
            // Directory doesn't exist
        }
        return null;
    }
    async listExecutions(workflowId) {
        const executions = [];
        if (workflowId) {
            const dir = path.join(this.basePath, 'executions', workflowId);
            try {
                const files = await fs.readdir(dir);
                for (const file of files) {
                    if (file.endsWith('.json')) {
                        const content = await fs.readFile(path.join(dir, file), 'utf-8');
                        executions.push(JSON.parse(content));
                    }
                }
            }
            catch (error) {
                // Directory doesn't exist
            }
        }
        else {
            // List all executions
            const executionsDir = path.join(this.basePath, 'executions');
            try {
                const workflowDirs = await fs.readdir(executionsDir);
                for (const workflowDir of workflowDirs) {
                    const dir = path.join(executionsDir, workflowDir);
                    const files = await fs.readdir(dir);
                    for (const file of files) {
                        if (file.endsWith('.json')) {
                            const content = await fs.readFile(path.join(dir, file), 'utf-8');
                            executions.push(JSON.parse(content));
                        }
                    }
                }
            }
            catch (error) {
                // Directory doesn't exist
            }
        }
        return executions;
    }
    // Template management
    async saveTemplate(template) {
        const dir = path.join(this.basePath, 'templates');
        await this.ensureDirectory(dir);
        const filePath = path.join(dir, `${template.id}.json`);
        await fs.writeFile(filePath, JSON.stringify(template, null, 2));
    }
    async loadTemplate(templateId) {
        const filePath = path.join(this.basePath, 'templates', `${templateId}.json`);
        try {
            const content = await fs.readFile(filePath, 'utf-8');
            return JSON.parse(content);
        }
        catch (error) {
            return null;
        }
    }
    async listTemplates(category) {
        const dir = path.join(this.basePath, 'templates');
        const templates = [];
        try {
            await this.ensureDirectory(dir);
            const files = await fs.readdir(dir);
            for (const file of files) {
                if (file.endsWith('.json')) {
                    const content = await fs.readFile(path.join(dir, file), 'utf-8');
                    const template = JSON.parse(content);
                    if (!category || template.category === category) {
                        templates.push(template);
                    }
                }
            }
        }
        catch (error) {
            // Directory doesn't exist
        }
        return templates;
    }
    // Metrics
    async getWorkflowMetrics(workflowId) {
        const executions = await this.listExecutions(workflowId);
        const metrics = {
            totalRuns: executions.length,
            successfulRuns: executions.filter(e => e.status === 'completed').length,
            failedRuns: executions.filter(e => e.status === 'failed').length,
            averageDuration: 0,
            taskMetrics: {},
            popularTriggers: {},
        };
        if (executions.length > 0) {
            const totalDuration = executions
                .filter(e => e.duration)
                .reduce((sum, e) => sum + (e.duration || 0), 0);
            metrics.averageDuration = totalDuration / executions.filter(e => e.duration).length;
            // Calculate task metrics
            for (const execution of executions) {
                for (const task of execution.tasks) {
                    if (!metrics.taskMetrics[task.taskId]) {
                        metrics.taskMetrics[task.taskId] = {
                            totalExecutions: 0,
                            successfulExecutions: 0,
                            failedExecutions: 0,
                            averageDuration: 0,
                            errorRate: 0,
                        };
                    }
                    const taskMetric = metrics.taskMetrics[task.taskId];
                    taskMetric.totalExecutions++;
                    if (task.status === 'completed') {
                        taskMetric.successfulExecutions++;
                    }
                    else if (task.status === 'failed') {
                        taskMetric.failedExecutions++;
                    }
                    if (task.duration) {
                        taskMetric.averageDuration =
                            (taskMetric.averageDuration * (taskMetric.totalExecutions - 1) + task.duration) /
                                taskMetric.totalExecutions;
                    }
                    taskMetric.errorRate = taskMetric.failedExecutions / taskMetric.totalExecutions;
                    taskMetric.lastExecution = execution.startTime;
                }
                // Track triggers
                if (execution.trigger) {
                    metrics.popularTriggers[execution.trigger] =
                        (metrics.popularTriggers[execution.trigger] || 0) + 1;
                }
            }
        }
        return metrics;
    }
    // Cleanup old executions
    async cleanupExecutions(olderThanDays = 30) {
        const cutoffDate = new Date();
        cutoffDate.setDate(cutoffDate.getDate() - olderThanDays);
        const executions = await this.listExecutions();
        let deletedCount = 0;
        for (const execution of executions) {
            const executionDate = new Date(execution.startTime);
            if (executionDate < cutoffDate) {
                const filePath = path.join(this.basePath, 'executions', execution.workflowId, `${execution.id}.json`);
                try {
                    await fs.unlink(filePath);
                    deletedCount++;
                }
                catch (error) {
                    // Ignore errors
                }
            }
        }
        return deletedCount;
    }
}
//# sourceMappingURL=store.js.map