"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.renderAppRunControlBlockForPreDrive = renderAppRunControlBlockForPreDrive;
exports.applyAppDialogRunControl = applyAppDialogRunControl;
exports.applyRegisteredAppDialogRunControls = applyRegisteredAppDialogRunControls;
const log_1 = require("../log");
const dialog_run_controls_1 = require("./dialog-run-controls");
const runtime_1 = require("./runtime");
const log = (0, log_1.createLogger)('apps-run-control');
function formatOwnerRef(block) {
    const owner = block.owner;
    if (owner.kind === 'human')
        return 'the human approver';
    return owner.memberId;
}
function formatTargetRef(block) {
    return block.targetRef.title ?? block.targetRef.id;
}
function canProjectAwaitAppAction(block) {
    if (block.actionClass === 'select') {
        return Array.isArray(block.optionsSummary) && block.optionsSummary.length > 0;
    }
    return true;
}
function projectAppActionLabel(block) {
    if (block.actionClass === 'input')
        return 'Provide information';
    if (block.actionClass === 'confirm')
        return 'Confirm and continue';
    return 'Choose an option';
}
function renderAppRunControlBlockForPreDrive(block) {
    if (block.blockKind === 'await_members') {
        const waitingList = block.waitingFor.map((entry) => entry.memberId).join(', ');
        return `Blocked while waiting for ${waitingList} on ${formatTargetRef(block)}. ${block.promptSummary}`;
    }
    if (block.blockKind === 'await_human') {
        const suffix = block.question ?? block.promptSummary;
        return `Blocked: human input is required for ${formatTargetRef(block)}. ${suffix}`;
    }
    if (!canProjectAwaitAppAction(block)) {
        return `View problem details. ${block.title}: ${block.promptSummary}`;
    }
    return `${projectAppActionLabel(block)} via ${formatOwnerRef(block)} for ${formatTargetRef(block)}. ${block.promptSummary}`;
}
async function applyAppDialogRunControl(params) {
    const controlId = params.controlId.trim();
    if (controlId === '') {
        throw new Error('dialog run control id cannot be empty');
    }
    const meta = (0, dialog_run_controls_1.getAppDialogRunControlMeta)(controlId);
    if (!meta) {
        throw new Error(`Unknown dialog run control: ${controlId}`);
    }
    const hostClient = await (0, runtime_1.waitForAppsHostClient)();
    return await hostClient.applyRunControl(controlId, params.payload);
}
async function applyRegisteredAppDialogRunControls(payload) {
    let recoveryAction;
    for (const control of (0, dialog_run_controls_1.listAppDialogRunControls)()) {
        let result;
        try {
            result = await applyAppDialogRunControl({
                controlId: control.id,
                payload,
            });
        }
        catch (error) {
            const err = error instanceof Error ? error : new Error(String(error));
            log.warn('App dialog run control failed; continuing without this app control', err, {
                controlId: control.id,
                dialogId: payload.dialog.selfId,
                rootId: payload.dialog.rootId,
                agentId: payload.agentId,
                taskDocPath: payload.taskDocPath,
                source: payload.source,
            });
            continue;
        }
        if (result.kind === 'reject') {
            return result;
        }
        if (result.kind === 'block') {
            return result;
        }
        if (recoveryAction === undefined && result.recoveryAction !== undefined) {
            recoveryAction = result.recoveryAction;
        }
    }
    return recoveryAction ? { kind: 'allow', recoveryAction } : { kind: 'allow' };
}
