"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCronScheduledWorkflows = exports.clearCronSchedule = exports.updateCronSchedule = exports.markAppIdContentDeployed = exports.markContentDeployed = exports.getVersionSnapshot = exports.getVersionHistory = exports.createVersionSnapshot = exports.findYamlWorkflowsByTags = exports.listYamlWorkflows = exports.updateYamlWorkflowStatus = exports.parseVersionFromYaml = void 0;
exports.checkTopicConflict = checkTopicConflict;
exports.createYamlWorkflow = createYamlWorkflow;
exports.getYamlWorkflow = getYamlWorkflow;
exports.getYamlWorkflowByName = getYamlWorkflowByName;
exports.updateYamlWorkflowVersion = updateYamlWorkflowVersion;
exports.updateYamlWorkflow = updateYamlWorkflow;
exports.deleteYamlWorkflow = deleteYamlWorkflow;
exports.discoverWorkflows = discoverWorkflows;
exports.getActiveYamlWorkflows = getActiveYamlWorkflows;
exports.listYamlWorkflowsByAppId = listYamlWorkflowsByAppId;
exports.getNextAppVersion = getNextAppVersion;
exports.getDistinctAppIds = getDistinctAppIds;
const db_1 = require("../../lib/db");
const sql_1 = require("./sql");
const db_utils_1 = require("./db-utils");
const db_versions_1 = require("./db-versions");
// Re-export functions from db-utils
var db_utils_2 = require("./db-utils");
Object.defineProperty(exports, "parseVersionFromYaml", { enumerable: true, get: function () { return db_utils_2.parseVersionFromYaml; } });
Object.defineProperty(exports, "updateYamlWorkflowStatus", { enumerable: true, get: function () { return db_utils_2.updateYamlWorkflowStatus; } });
Object.defineProperty(exports, "listYamlWorkflows", { enumerable: true, get: function () { return db_utils_2.listYamlWorkflows; } });
Object.defineProperty(exports, "findYamlWorkflowsByTags", { enumerable: true, get: function () { return db_utils_2.findYamlWorkflowsByTags; } });
// Re-export version history and cron scheduling from db-versions
var db_versions_2 = require("./db-versions");
Object.defineProperty(exports, "createVersionSnapshot", { enumerable: true, get: function () { return db_versions_2.createVersionSnapshot; } });
Object.defineProperty(exports, "getVersionHistory", { enumerable: true, get: function () { return db_versions_2.getVersionHistory; } });
Object.defineProperty(exports, "getVersionSnapshot", { enumerable: true, get: function () { return db_versions_2.getVersionSnapshot; } });
Object.defineProperty(exports, "markContentDeployed", { enumerable: true, get: function () { return db_versions_2.markContentDeployed; } });
Object.defineProperty(exports, "markAppIdContentDeployed", { enumerable: true, get: function () { return db_versions_2.markAppIdContentDeployed; } });
Object.defineProperty(exports, "updateCronSchedule", { enumerable: true, get: function () { return db_versions_2.updateCronSchedule; } });
Object.defineProperty(exports, "clearCronSchedule", { enumerable: true, get: function () { return db_versions_2.clearCronSchedule; } });
Object.defineProperty(exports, "getCronScheduledWorkflows", { enumerable: true, get: function () { return db_versions_2.getCronScheduledWorkflows; } });
/**
 * Check whether a graph_topic is already in use by a non-archived workflow
 * in the same namespace. Returns the conflicting workflow name, or null.
 */
async function checkTopicConflict(appId, graphTopic, excludeId) {
    const pool = (0, db_1.getPool)();
    const { rows } = await pool.query(sql_1.CHECK_TOPIC_UNIQUE, [appId, graphTopic]);
    if (rows.length === 0)
        return null;
    if (excludeId && rows[0].id === excludeId)
        return null;
    return rows[0].name;
}
async function createYamlWorkflow(input) {
    const pool = (0, db_1.getPool)();
    const { rows } = await pool.query(sql_1.CREATE_YAML_WORKFLOW, [
        input.name,
        input.description || null,
        input.app_id,
        input.app_version || (0, db_utils_1.parseVersionFromYaml)(input.yaml_content) || '0',
        input.source_workflow_id || null,
        input.source_workflow_type || null,
        input.yaml_content,
        input.graph_topic,
        JSON.stringify(input.input_schema || {}),
        JSON.stringify(input.output_schema || {}),
        JSON.stringify(input.activity_manifest || []),
        JSON.stringify(input.input_field_meta || []),
        input.original_prompt || null,
        input.category || null,
        input.tags || [],
        input.metadata ? JSON.stringify(input.metadata) : null,
        input.set_id || null,
        input.set_role || null,
        input.set_build_order ?? null,
    ]);
    const record = rows[0];
    await (0, db_versions_1.createVersionSnapshot)(record.id, 1, record.yaml_content, input.activity_manifest || [], input.input_schema || {}, input.output_schema || {}, input.input_field_meta || [], 'Initial version');
    return record;
}
async function getYamlWorkflow(id) {
    const pool = (0, db_1.getPool)();
    const { rows } = await pool.query(sql_1.GET_YAML_WORKFLOW, [id]);
    return rows[0] || null;
}
async function getYamlWorkflowByName(name) {
    const pool = (0, db_1.getPool)();
    const { rows } = await pool.query(sql_1.GET_YAML_WORKFLOW_BY_NAME, [name]);
    return rows[0] || null;
}
async function updateYamlWorkflowVersion(id, version) {
    const pool = (0, db_1.getPool)();
    await pool.query(sql_1.UPDATE_YAML_WORKFLOW_VERSION, [id, version]);
}
async function updateYamlWorkflow(id, updates) {
    const pool = (0, db_1.getPool)();
    const sets = [];
    const values = [];
    let idx = 1;
    const yamlChanging = updates.yaml_content !== undefined;
    if (updates.name !== undefined) {
        sets.push(`name = $${idx++}`);
        values.push(updates.name);
    }
    if (updates.description !== undefined) {
        sets.push(`description = $${idx++}`);
        values.push(updates.description);
    }
    if (updates.app_id !== undefined) {
        sets.push(`app_id = $${idx++}`);
        values.push(updates.app_id);
    }
    if (updates.yaml_content !== undefined) {
        sets.push(`yaml_content = $${idx++}`);
        values.push(updates.yaml_content);
    }
    if (updates.graph_topic !== undefined) {
        sets.push(`graph_topic = $${idx++}`);
        values.push(updates.graph_topic);
    }
    if (updates.input_schema !== undefined) {
        sets.push(`input_schema = $${idx++}`);
        values.push(JSON.stringify(updates.input_schema));
    }
    if (updates.output_schema !== undefined) {
        sets.push(`output_schema = $${idx++}`);
        values.push(JSON.stringify(updates.output_schema));
    }
    if (updates.activity_manifest !== undefined) {
        sets.push(`activity_manifest = $${idx++}`);
        values.push(JSON.stringify(updates.activity_manifest));
    }
    if (updates.tags !== undefined) {
        sets.push(`tags = $${idx++}`);
        values.push(updates.tags);
    }
    if (updates.metadata !== undefined) {
        sets.push(`metadata = $${idx++}`);
        values.push(JSON.stringify(updates.metadata));
    }
    if (yamlChanging) {
        sets.push(`content_version = content_version + 1`);
        const parsedVersion = (0, db_utils_1.parseVersionFromYaml)(updates.yaml_content);
        if (parsedVersion) {
            sets.push(`app_version = $${idx++}`);
            values.push(parsedVersion);
        }
    }
    if (sets.length === 0)
        return getYamlWorkflow(id);
    values.push(id);
    const { rows } = await pool.query(`UPDATE lt_yaml_workflows SET ${sets.join(', ')} WHERE id = $${idx} RETURNING *`, values);
    const record = rows[0] || null;
    if (record && yamlChanging) {
        await (0, db_versions_1.createVersionSnapshot)(record.id, record.content_version, record.yaml_content, record.activity_manifest, record.input_schema, record.output_schema, record.input_field_meta);
    }
    return record;
}
async function deleteYamlWorkflow(id) {
    const pool = (0, db_1.getPool)();
    const { rowCount } = await pool.query(sql_1.DELETE_YAML_WORKFLOW, [id]);
    return (rowCount || 0) > 0;
}
/**
 * Ranked discovery: find active workflows matching the user's prompt
 * via full-text search (tsvector) + tag overlap + optional category filter.
 */
async function discoverWorkflows(prompt, tags, category, limit = 5) {
    const pool = (0, db_1.getPool)();
    const { rows } = await pool.query(sql_1.DISCOVER_WORKFLOWS, [prompt, tags, category || null, limit]);
    return rows;
}
async function getActiveYamlWorkflows() {
    const pool = (0, db_1.getPool)();
    const { rows } = await pool.query(sql_1.GET_ACTIVE_YAML_WORKFLOWS);
    return rows;
}
async function listYamlWorkflowsByAppId(appId) {
    const pool = (0, db_1.getPool)();
    const { rows } = await pool.query(sql_1.LIST_BY_APP_ID, [appId]);
    return rows;
}
/**
 * Return the next app-level version for a namespace.
 *
 * Each deploy of an app (namespace) must use a strictly increasing integer
 * version. This queries the current max across all non-archived workflows
 * in the namespace and returns max + 1.
 *
 * A new namespace with no workflows returns '1'.
 * An existing namespace with one active tool at v1 returns '2' when a
 * second tool is added -- even though that second tool is "version 1" of itself.
 */
async function getNextAppVersion(appId) {
    const pool = (0, db_1.getPool)();
    const { rows } = await pool.query(sql_1.GET_MAX_APP_VERSION, [appId]);
    const max = parseInt(rows[0]?.max_version ?? '0', 10);
    return String(max + 1);
}
async function getDistinctAppIds() {
    const pool = (0, db_1.getPool)();
    const { rows } = await pool.query(sql_1.GET_DISTINCT_APP_IDS);
    return rows.map((r) => r.app_id);
}
