"use strict";
/**
 * Workflow Parser
 * Parses YAML workflow files into typed Workflow objects
 */
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.WorkflowParser = void 0;
const yaml = __importStar(require("js-yaml"));
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const zod_1 = require("zod");
const workflow_schema_1 = require("./workflow-schema");
const extended_workflow_schema_1 = require("./extended-workflow-schema");
const reference_resolver_1 = require("./reference-resolver");
const schema_error_formatter_1 = require("./schema-error-formatter");
class WorkflowParser {
    referenceResolver;
    constructor() {
        this.referenceResolver = new reference_resolver_1.ReferenceResolver();
    }
    /**
     * Parse a workflow file from disk
     */
    async parseFile(filePath) {
        const absolutePath = path.resolve(filePath);
        if (!fs.existsSync(absolutePath)) {
            throw new Error(`Workflow file not found: ${absolutePath}`);
        }
        const content = fs.readFileSync(absolutePath, 'utf-8');
        return this.parseString(content, absolutePath);
    }
    /**
     * Parse a workflow from a YAML string
     * Detects and parses both event-driven and extended workflow schemas
     */
    async parseString(yamlContent, source = 'string') {
        try {
            const parsed = yaml.load(yamlContent);
            if (!parsed) {
                throw new Error('Empty workflow file');
            }
            // Resolve $ref fields
            const resolved = await this.referenceResolver.resolve(parsed, {
                basePath: source === 'string' ? process.cwd() : source,
            });
            // Detect which schema to use based on presence of extended fields
            const hasExtendedFields = resolved.technology !== undefined ||
                resolved.models !== undefined ||
                resolved.events !== undefined ||
                resolved.actors !== undefined ||
                resolved.components !== undefined ||
                resolved.workflows !== undefined;
            let extendedWorkflow;
            if (hasExtendedFields) {
                // Parse with extended schema
                try {
                    extendedWorkflow = extended_workflow_schema_1.ExtendedWorkflowSchema.parse(resolved);
                }
                catch (error) {
                    if (error instanceof zod_1.ZodError) {
                        const formattedError = schema_error_formatter_1.SchemaErrorFormatter.format(error, source);
                        throw new Error(formattedError);
                    }
                    throw error;
                }
            }
            // Also parse with legacy schema for backwards compatibility
            const workflow = workflow_schema_1.WorkflowSchema.parse(resolved);
            return {
                workflow,
                extendedWorkflow,
            };
        }
        catch (error) {
            if (error instanceof yaml.YAMLException) {
                const formattedError = schema_error_formatter_1.SchemaErrorFormatter.formatSimple(error.message, 'YAML Syntax Error', 'Check your YAML syntax - common issues include incorrect indentation, missing colons, or unquoted strings with special characters');
                throw new Error(formattedError);
            }
            if (error instanceof zod_1.ZodError) {
                const formattedError = schema_error_formatter_1.SchemaErrorFormatter.format(error, source);
                throw new Error(formattedError);
            }
            throw error;
        }
    }
    /**
     * Parse multiple workflow files from a directory
     */
    async parseDirectory(dirPath) {
        const absolutePath = path.resolve(dirPath);
        if (!fs.existsSync(absolutePath)) {
            throw new Error(`Directory not found: ${absolutePath}`);
        }
        const files = fs.readdirSync(absolutePath)
            .filter(file => file.endsWith('.workflow.yaml') || file.endsWith('.workflow.yml'));
        return Promise.all(files.map(file => {
            const filePath = path.join(absolutePath, file);
            return this.parseFile(filePath);
        }));
    }
    /**
     * Get all files referenced by a workflow file (for dependency tracking)
     */
    getReferencedFiles(filePath) {
        const absolutePath = path.resolve(filePath);
        if (!fs.existsSync(absolutePath)) {
            throw new Error(`Workflow file not found: ${absolutePath}`);
        }
        const content = fs.readFileSync(absolutePath, 'utf-8');
        const parsed = yaml.load(content);
        if (!parsed) {
            return [];
        }
        return this.referenceResolver.getAllReferencedFiles(parsed, absolutePath);
    }
}
exports.WorkflowParser = WorkflowParser;
//# sourceMappingURL=workflow-parser.js.map