import { selectOption } from '../../shared/prompt/index.js';
import { getBookmarkedWorkflows, addBookmark, removeBookmark } from '../../infra/config/global/index.js';
import { info } from '../../shared/ui/index.js';
import { sanitizeTerminalText } from '../../shared/utils/index.js';
import { applyBookmarks, parseCategorySelection, CATEGORY_VALUE_PREFIX, } from './options.js';
const CUSTOM_CATEGORY_PREFIX = '__custom_category__:';
function getSelectableBookmarkedWorkflows(categorized) {
    const selectableWorkflows = new Set(categorized.allWorkflows.keys());
    return getBookmarkedWorkflows().filter((workflowName) => selectableWorkflows.has(workflowName));
}
function buildCategoryLevelOptions(categories, workflows) {
    const options = [];
    const categoryMap = new Map();
    for (const category of categories) {
        options.push({
            label: `📁 ${sanitizeTerminalText(category.name)}/`,
            value: `${CATEGORY_VALUE_PREFIX}${category.name}`,
        });
        categoryMap.set(category.name, category);
    }
    for (const workflowName of workflows) {
        options.push({
            label: `🎼 ${sanitizeTerminalText(workflowName)}`,
            value: workflowName,
        });
    }
    return { options, categoryMap };
}
async function selectWorkflowFromCategoryTree(categories, hasSourceSelection, rootWorkflows = []) {
    if (categories.length === 0 && rootWorkflows.length === 0) {
        info('No workflows available for configured categories.');
        return null;
    }
    const stack = [];
    while (true) {
        const currentNode = stack.at(-1);
        const currentCategories = currentNode ? currentNode.children : categories;
        const currentWorkflows = currentNode ? currentNode.workflows : rootWorkflows;
        const currentPathLabel = sanitizeTerminalText(stack.map((node) => node.name).join(' / '));
        const { options, categoryMap } = buildCategoryLevelOptions(currentCategories, currentWorkflows);
        if (options.length === 0) {
            if (stack.length === 0) {
                info('No workflows available for configured categories.');
                return null;
            }
            stack.pop();
            continue;
        }
        const buildOptionsWithBookmarks = () => applyBookmarks(options, getBookmarkedWorkflows());
        const message = currentPathLabel.length > 0
            ? `Select workflow in ${currentPathLabel}:`
            : 'Select workflow category:';
        const selected = await selectOption(message, buildOptionsWithBookmarks(), {
            cancelLabel: (stack.length > 0 || hasSourceSelection) ? '← Go back' : 'Cancel',
            onKeyPress: (key, value) => {
                if (parseCategorySelection(value)) {
                    return null;
                }
                if (key === 'b') {
                    addBookmark(value);
                    return buildOptionsWithBookmarks();
                }
                if (key === 'r') {
                    removeBookmark(value);
                    return buildOptionsWithBookmarks();
                }
                return null;
            },
        });
        if (!selected) {
            if (stack.length > 0) {
                stack.pop();
                continue;
            }
            return null;
        }
        const categoryName = parseCategorySelection(selected);
        if (!categoryName) {
            return selected;
        }
        const nextNode = categoryMap.get(categoryName);
        if (nextNode) {
            stack.push(nextNode);
        }
    }
}
async function selectTopLevelWorkflowOption(categorized) {
    const buildOptions = () => {
        const options = [];
        for (const workflowName of getSelectableBookmarkedWorkflows(categorized)) {
            options.push({
                label: `🎼 ${sanitizeTerminalText(workflowName)} [*]`,
                value: workflowName,
            });
        }
        for (const category of categorized.categories) {
            options.push({
                label: `📁 ${sanitizeTerminalText(category.name)}/`,
                value: `${CUSTOM_CATEGORY_PREFIX}${category.name}`,
            });
        }
        return options;
    };
    if (buildOptions().length === 0) {
        return null;
    }
    const result = await selectOption('Select workflow:', buildOptions(), {
        onKeyPress: (key, value) => {
            if (value.startsWith(CUSTOM_CATEGORY_PREFIX)) {
                return null;
            }
            if (key === 'b') {
                addBookmark(value);
                return buildOptions();
            }
            if (key === 'r') {
                removeBookmark(value);
                return buildOptions();
            }
            return null;
        },
    });
    if (!result) {
        return null;
    }
    if (!result.startsWith(CUSTOM_CATEGORY_PREFIX)) {
        return { type: 'workflow', name: result };
    }
    const categoryName = result.slice(CUSTOM_CATEGORY_PREFIX.length);
    const node = categorized.categories.find((category) => category.name === categoryName);
    return node ? { type: 'category', node } : null;
}
export async function selectWorkflowFromCategorizedWorkflows(categorized) {
    while (true) {
        const selection = await selectTopLevelWorkflowOption(categorized);
        if (!selection) {
            return null;
        }
        if (selection.type === 'workflow') {
            return selection.name;
        }
        const workflow = await selectWorkflowFromCategoryTree(selection.node.children, true, selection.node.workflows);
        if (workflow) {
            return workflow;
        }
    }
}
//# sourceMappingURL=categorizedSelection.js.map