"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.switchTabExecutor = void 0;
const switchTabHelper_1 = require("./switchTabHelper");
exports.switchTabExecutor = {
    needsFind: () => false,
    getStepType: () => 'switch-tab',
    execute: async (payload, stateProvider, eventHandler, logger) => {
        const toolParams = payload.toolCall
            .toolParams;
        if (!(toolParams.tab_id || toolParams.title || toolParams.url)) {
            logger.error('Switch Tab executor requires at least one of: tab_id, title, or url');
            return {
                success: false,
                errorCause: 'IllegalArguments',
                errorMessage: 'Switch Tab requires at least one of: tab_id, title, or url',
            };
        }
        const trainingContext = stateProvider.getTrainingContext();
        let targetTabId = toolParams.tab_id;
        if (!targetTabId) {
            logger.info(`Searching for tab by title: "${toolParams.title}" or URL: "${toolParams.url}"`);
            const trackedTabs = await trainingContext.getTrackedTabsInfo();
            const matchingTab = trackedTabs.find((tab) => {
                if (toolParams.url && tab.url === toolParams.url) {
                    return true;
                }
                if (toolParams.title && tab.title === toolParams.title) {
                    return true;
                }
                return false;
            });
            if (matchingTab) {
                targetTabId = matchingTab.tab_id;
                logger.info(`Found matching tab: ${targetTabId}`);
            }
            else {
                logger.error(`No tab found matching title: "${toolParams.title}" or URL: "${toolParams.url}"`);
                return {
                    success: false,
                    errorCause: 'RecordFailed',
                    errorMessage: `No tab found matching the provided title or URL`,
                };
            }
        }
        const existingSelectorInfo = trainingContext.getTabSelectorInfo(targetTabId);
        if (!existingSelectorInfo) {
            logger.info(`Tracking new tab ${targetTabId}`);
            trainingContext.trackTrainingTab(targetTabId);
        }
        const currentTabId = trainingContext.getCurrentTab();
        if (String(currentTabId) === String(targetTabId)) {
            logger.info(`Already on tab ${targetTabId}, no switch context step needed`);
            return {
                success: true,
                message: `Already on the requested tab (tab_id: ${targetTabId}). No switch context step was recorded.`,
            };
        }
        return (0, switchTabHelper_1.recordSwitchTabAndSync)(targetTabId, stateProvider, eventHandler, logger);
    },
};
