"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.ltCreateTask = ltCreateTask;
exports.ltStartTask = ltStartTask;
exports.ltCompleteTask = ltCompleteTask;
exports.ltEscalateTask = ltEscalateTask;
exports.ltFailTask = ltFailTask;
exports.ltAppendMilestones = ltAppendMilestones;
exports.ltGetTaskByWorkflowId = ltGetTaskByWorkflowId;
exports.ltGetTask = ltGetTask;
const taskService = __importStar(require("../../task"));
const publish_1 = require("../../../lib/events/publish");
const db_1 = require("../../../lib/db");
const sql_1 = require("../../user/sql");
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
/** Resolve an identifier to a verified lt_users UUID. Returns undefined if not found. */
async function resolveUserUuid(identifier) {
    if (!identifier)
        return undefined;
    const pool = (0, db_1.getPool)();
    if (UUID_RE.test(identifier)) {
        const { rows } = await pool.query(sql_1.VERIFY_USER_BY_ID, [identifier]);
        return rows[0]?.id ?? undefined;
    }
    const { rows } = await pool.query(sql_1.GET_USER_BY_EXTERNAL_ID, [identifier]);
    return rows[0]?.id ?? undefined;
}
/**
 * Create a task record when a Long Tail workflow starts.
 */
async function ltCreateTask(input) {
    const initiatedByUuid = await resolveUserUuid(input.initiatedBy);
    const task = await taskService.createTask({
        workflow_id: input.workflowId,
        workflow_type: input.workflowType,
        lt_type: input.ltType,
        task_queue: input.taskQueue,
        signal_id: input.signalId,
        parent_workflow_id: input.parentWorkflowId,
        origin_id: input.originId,
        parent_id: input.parentId,
        envelope: input.envelope,
        metadata: input.metadata,
        trace_id: input.traceId,
        span_id: input.spanId,
        initiated_by: initiatedByUuid,
        principal_type: input.principalType,
        executing_as: input.executingAs,
        status: input.status,
    });
    (0, publish_1.publishTaskEvent)({
        type: 'task.created',
        source: 'interceptor',
        workflowId: input.workflowId,
        workflowName: input.workflowType,
        taskQueue: input.taskQueue || 'unknown',
        taskId: task.id,
        originId: input.originId,
        status: input.status || 'pending',
    });
    return task.id;
}
/**
 * Mark a task as in_progress.
 */
async function ltStartTask(taskId) {
    await taskService.updateTask(taskId, { status: 'in_progress' });
}
/**
 * Mark a task as completed with result data and milestones.
 */
async function ltCompleteTask(input) {
    await taskService.updateTask(input.taskId, {
        status: 'completed',
        completed_at: new Date(),
        data: input.data,
        milestones: input.milestones,
    });
    // Publish task.completed event
    if (input.workflowId) {
        (0, publish_1.publishTaskEvent)({
            type: 'task.completed',
            source: 'orchestrator',
            workflowId: input.workflowId,
            workflowName: input.workflowName || 'unknown',
            taskQueue: input.taskQueue || 'unknown',
            taskId: input.taskId,
            status: 'completed',
            milestones: input.milestones,
        });
    }
    // Publish milestone event from orchestrator context
    if (input.milestones?.length && input.workflowId) {
        (0, publish_1.publishMilestoneEvent)({
            source: 'orchestrator',
            workflowId: input.workflowId,
            workflowName: input.workflowName || 'unknown',
            taskQueue: input.taskQueue || 'unknown',
            taskId: input.taskId,
            milestones: input.milestones,
        });
    }
}
/**
 * Mark a task as needing intervention (escalated).
 */
async function ltEscalateTask(taskId) {
    await taskService.updateTask(taskId, { status: 'needs_intervention' });
}
/**
 * Mark a task as failed.
 */
async function ltFailTask(input) {
    await taskService.updateTask(input.taskId, {
        status: 'needs_intervention',
        error: input.error,
    });
}
/**
 * Append milestones to a task (used by activity interceptor).
 */
async function ltAppendMilestones(input) {
    await taskService.appendMilestones(input.taskId, input.milestones);
}
/**
 * Look up a task by workflow ID. Used by the interceptor to detect
 * whether a task was already created by executeLT (orchestrated mode)
 * or needs to be created by the interceptor (standalone mode).
 */
async function ltGetTaskByWorkflowId(workflowId) {
    return taskService.getTaskByWorkflowId(workflowId);
}
/**
 * Look up a task by its primary ID.
 * Used by the interceptor on re-runs to find the original task.
 */
async function ltGetTask(taskId) {
    return taskService.getTask(taskId);
}
