import { getMidsceneLocationSchema } from "../common.mjs";
import { getDebug } from "@midscene/shared/logger";
import { z } from "zod";
function _define_property(obj, key, value) {
    if (key in obj) Object.defineProperty(obj, key, {
        value: value,
        enumerable: true,
        configurable: true,
        writable: true
    });
    else obj[key] = value;
    return obj;
}
class AbstractInterface {
    constructor(){
        _define_property(this, "mjpegStreamUrl", void 0);
        _define_property(this, "inputPrimitives", void 0);
    }
}
const defineAction = (config)=>config;
function pointFromLocate(locate, missingMessage) {
    if (!locate) throw new Error(missingMessage);
    return {
        x: locate.center[0],
        y: locate.center[1]
    };
}
function defineLocatedPointAction(config) {
    return defineAction({
        name: config.name,
        description: config.description,
        interfaceAlias: config.interfaceAlias,
        paramSchema: config.paramSchema,
        sample: config.sample,
        call: async (param)=>{
            await config.call(pointFromLocate(param.locate, config.missingLocateMessage), param);
        }
    });
}
const actionTapParamSchema = z.object({
    locate: getMidsceneLocationSchema().describe('The element to be tapped')
});
const defineActionTap = (tap)=>defineLocatedPointAction({
        name: 'Tap',
        description: 'Tap the element',
        interfaceAlias: 'aiTap',
        paramSchema: actionTapParamSchema,
        sample: {
            locate: {
                prompt: 'the "Submit" button'
            }
        },
        missingLocateMessage: 'Element not found, cannot tap',
        call: async (point)=>{
            await tap(point);
        }
    });
const actionRightClickParamSchema = z.object({
    locate: getMidsceneLocationSchema().describe('The element to be right clicked')
});
const defineActionRightClick = (rightClick)=>defineLocatedPointAction({
        name: 'RightClick',
        description: 'Right click the element',
        interfaceAlias: 'aiRightClick',
        paramSchema: actionRightClickParamSchema,
        sample: {
            locate: {
                prompt: 'the file icon on the desktop'
            }
        },
        missingLocateMessage: 'Element not found, cannot right click',
        call: async (point)=>{
            await rightClick(point);
        }
    });
const actionDoubleClickParamSchema = z.object({
    locate: getMidsceneLocationSchema().describe('The element to be double clicked')
});
const defineActionDoubleClick = (doubleClick)=>defineLocatedPointAction({
        name: 'DoubleClick',
        description: 'Double click the element',
        interfaceAlias: 'aiDoubleClick',
        paramSchema: actionDoubleClickParamSchema,
        sample: {
            locate: {
                prompt: 'the folder icon'
            }
        },
        missingLocateMessage: 'Element not found, cannot double click',
        call: async (point)=>{
            await doubleClick(point);
        }
    });
const actionHoverParamSchema = z.object({
    locate: getMidsceneLocationSchema().describe('The element to be hovered')
});
const defineActionHover = (hover)=>defineLocatedPointAction({
        name: 'Hover',
        description: 'Move the mouse to the element',
        interfaceAlias: 'aiHover',
        paramSchema: actionHoverParamSchema,
        sample: {
            locate: {
                prompt: 'the navigation menu item "Products"'
            }
        },
        missingLocateMessage: 'Element not found, cannot hover',
        call: async (point)=>{
            await hover(point);
        }
    });
const inputLocateDescription = 'the position of the placeholder or text content in the target input field. If there is no content, locate the center of the input field.';
const actionInputParamSchema = z.object({
    value: z.union([
        z.string(),
        z.number()
    ]).transform((val)=>String(val)).describe('The text to input. Provide the final content for replace mode, only the inserted characters for typeOnly mode, or an empty string when using clear mode to remove existing text.'),
    locate: getMidsceneLocationSchema().describe(inputLocateDescription).optional(),
    mode: z["enum"]([
        'replace',
        'clear',
        'typeOnly'
    ]).default('replace').describe('Input mode: "replace" (default) - clear the field and input the value; "typeOnly" - type the value directly without clearing the field first, and should be set explicitly for incremental edits after moving the cursor; "clear" - clear the field without inputting new text.'),
    autoDismissKeyboard: z.boolean().optional().describe('If true, the keyboard will be dismissed after the input is completed. Do not set it unless the user asks you to do so.')
});
const defineActionInput = (keyboard)=>defineAction({
        name: 'Input',
        description: 'Input the value into the element',
        interfaceAlias: 'aiInput',
        paramSchema: actionInputParamSchema,
        sample: {
            value: 'test@example.com',
            locate: {
                prompt: 'the email input field'
            }
        },
        call: async (param)=>{
            if ('append' === param.mode) param.mode = 'typeOnly';
            if ('clear' === param.mode) return void await keyboard.clearInput(param.locate);
            if (!param || !param.value) return;
            await keyboard.typeText(param.value, {
                target: param.locate,
                replace: 'typeOnly' !== param.mode,
                autoDismissKeyboard: param.autoDismissKeyboard
            });
        }
    });
const actionKeyboardPressParamSchema = z.object({
    locate: getMidsceneLocationSchema().describe('The element to be clicked before pressing the key').optional(),
    keyName: z.string().describe("The key to be pressed. Use '+' for key combinations, e.g., 'Control+A', 'Shift+Enter'")
});
const defineActionKeyboardPress = (keyboardPress)=>defineAction({
        name: 'KeyboardPress',
        description: 'Press a key or key combination, like "Enter", "Tab", "Escape", or "Control+A", "Shift+Enter". Do not use this to type text.',
        interfaceAlias: 'aiKeyboardPress',
        paramSchema: actionKeyboardPressParamSchema,
        sample: {
            keyName: 'Enter'
        },
        call: async (param)=>{
            await keyboardPress(param.keyName, {
                target: param.locate
            });
        }
    });
const actionScrollParamSchema = z.object({
    scrollType: z["enum"]([
        'singleAction',
        'scrollToBottom',
        'scrollToTop',
        'scrollToRight',
        'scrollToLeft'
    ]).default('singleAction').describe('The scroll behavior: "singleAction" for a single scroll action, "scrollToBottom" for scrolling all the way to the bottom by rapidly scrolling 5-10 times (skipping intermediate content until reaching the bottom), "scrollToTop" for scrolling all the way to the top by rapidly scrolling 5-10 times (skipping intermediate content until reaching the top), "scrollToRight" for scrolling all the way to the right by rapidly scrolling multiple times, "scrollToLeft" for scrolling all the way to the left by rapidly scrolling multiple times'),
    direction: z["enum"]([
        'down',
        'up',
        'right',
        'left'
    ]).default('down').describe('The direction to scroll. Only effective when scrollType is "singleAction".'),
    distance: z.number().nullable().optional().describe('The distance in pixels to scroll'),
    locate: getMidsceneLocationSchema().optional().describe('Describe the target element to be scrolled on, like "the table" or "the list" or "the content area" or "the scrollable area". Do NOT provide a general intent like "scroll to find some element"')
});
const defineActionScroll = (scroll)=>defineAction({
        name: 'Scroll',
        description: 'Scroll the page or a scrollable element to browse content. This is the preferred way to scroll on all platforms, including mobile. Supports scrollToBottom/scrollToTop for boundary navigation. Default: direction `down`, scrollType `singleAction`, distance `null`.',
        interfaceAlias: 'aiScroll',
        paramSchema: actionScrollParamSchema,
        sample: {
            direction: 'down',
            scrollType: 'singleAction',
            locate: {
                prompt: 'the center of the product list area'
            }
        },
        call: async (param)=>{
            await scroll(param);
        }
    });
const actionDragAndDropParamSchema = z.object({
    from: getMidsceneLocationSchema().describe('The position to be dragged'),
    to: getMidsceneLocationSchema().describe('The position to be dropped')
});
const defineActionDragAndDrop = (dragAndDrop)=>defineAction({
        name: 'DragAndDrop',
        description: 'Pick up a specific UI element and move it to a new position (e.g., reorder a card, move a file into a folder, sort list items). The element itself moves with your finger/mouse.',
        interfaceAlias: 'aiDragAndDrop',
        paramSchema: actionDragAndDropParamSchema,
        sample: {
            from: {
                prompt: 'the "report.pdf" file icon'
            },
            to: {
                prompt: 'the upload drop zone'
            }
        },
        call: async (param)=>{
            const from = param.from;
            const to = param.to;
            if (!from) throw new Error('missing "from" param for drag and drop');
            if (!to) throw new Error('missing "to" param for drag and drop');
            await dragAndDrop({
                x: from.center[0],
                y: from.center[1]
            }, {
                x: to.center[0],
                y: to.center[1]
            });
        }
    });
const ActionLongPressParamSchema = z.object({
    locate: getMidsceneLocationSchema().describe('The element to be long pressed'),
    duration: z.number().optional().describe('Long press duration in milliseconds')
});
const defineActionLongPress = (longPress)=>defineLocatedPointAction({
        name: 'LongPress',
        description: 'Long press the element',
        interfaceAlias: 'aiLongPress',
        paramSchema: ActionLongPressParamSchema,
        sample: {
            locate: {
                prompt: 'the message bubble'
            }
        },
        missingLocateMessage: 'LongPress requires an element to be located',
        call: async (point, param)=>{
            await longPress(point, {
                duration: param.duration
            });
        }
    });
const ActionSwipeParamSchema = z.object({
    start: getMidsceneLocationSchema().optional().describe('Starting point of the swipe gesture, if not specified, the center of the page will be used'),
    direction: z["enum"]([
        'up',
        'down',
        'left',
        'right'
    ]).optional().describe('The direction to swipe (required when using distance). The direction means the direction of the finger swipe.'),
    distance: z.number().optional().describe('The distance in pixels to swipe (mutually exclusive with end)'),
    end: getMidsceneLocationSchema().optional().describe('Ending point of the swipe gesture (mutually exclusive with distance)'),
    duration: z.number().default(300).describe('Duration of the swipe gesture in milliseconds'),
    repeat: z.number().optional().describe('The number of times to repeat the swipe gesture. 1 for default, 0 for infinite (e.g. endless swipe until the end of the page)')
});
function normalizeMobileSwipeParam(param, screenSize) {
    const { width, height } = screenSize;
    const { start, end } = param;
    const startPoint = start ? {
        x: start.center[0],
        y: start.center[1]
    } : {
        x: width / 2,
        y: height / 2
    };
    let endPoint;
    if (end) endPoint = {
        x: end.center[0],
        y: end.center[1]
    };
    else if (param.distance) {
        const direction = param.direction;
        if (!direction) throw new Error('direction is required for swipe gesture');
        endPoint = {
            x: startPoint.x + ('right' === direction ? param.distance : 'left' === direction ? -param.distance : 0),
            y: startPoint.y + ('down' === direction ? param.distance : 'up' === direction ? -param.distance : 0)
        };
    } else throw new Error('Either end or distance must be specified for swipe gesture');
    endPoint.x = Math.max(0, Math.min(endPoint.x, width));
    endPoint.y = Math.max(0, Math.min(endPoint.y, height));
    const duration = param.duration ?? 300;
    let repeatCount = 'number' == typeof param.repeat ? param.repeat : 1;
    if (0 === repeatCount) repeatCount = 10;
    return {
        startPoint,
        endPoint,
        duration,
        repeatCount
    };
}
const defineActionSwipe = (config)=>defineAction({
        name: 'Swipe',
        description: 'Perform a touch gesture for interactions beyond regular scrolling (e.g., adjust a continuous control such as a slider, flip pages in a carousel, dismiss a notification, swipe-to-delete a list item). For regular content scrolling, use Scroll instead. Use "distance" + "direction" for relative movement, or "start" + "end" for precise endpoint movement.',
        paramSchema: ActionSwipeParamSchema,
        sample: {
            start: {
                prompt: 'center of the notification'
            },
            end: {
                prompt: 'upper edge of the screen'
            }
        },
        call: async (param)=>{
            const { startPoint, endPoint, duration, repeatCount } = normalizeMobileSwipeParam(param, await config.size());
            for(let i = 0; i < repeatCount; i++)await config.swipe(startPoint, endPoint, {
                duration
            });
        }
    });
const actionClearInputParamSchema = z.object({
    locate: getMidsceneLocationSchema().describe('The input field to be cleared').optional()
});
const defineActionClearInput = (clearInput)=>defineAction({
        name: 'ClearInput',
        description: inputLocateDescription,
        interfaceAlias: 'aiClearInput',
        paramSchema: actionClearInputParamSchema,
        sample: {
            locate: {
                prompt: 'the search input field'
            }
        },
        call: async (param)=>{
            await clearInput(param.locate);
        }
    });
const actionCursorMoveParamSchema = z.object({
    direction: z["enum"]([
        'left',
        'right'
    ]).describe('The direction to move the cursor'),
    times: z.number().int().min(1).default(1).describe('The number of times to move the cursor in the specified direction')
});
const defineActionCursorMove = (config)=>defineAction({
        name: 'CursorMove',
        description: 'Move the text cursor (caret) left or right within an input field or text area. Use this to reposition the cursor without selecting text.',
        paramSchema: actionCursorMoveParamSchema,
        sample: {
            direction: 'left',
            times: 3
        },
        call: async (param)=>{
            const times = param.times ?? 1;
            if (config.keyboard.cursorMove) return void await config.keyboard.cursorMove(param.direction, times);
            const wait = config.sleep ?? ((timeMs)=>new Promise((resolve)=>setTimeout(resolve, timeMs)));
            const arrowKey = 'left' === param.direction ? 'ArrowLeft' : 'ArrowRight';
            for(let i = 0; i < times; i++){
                await config.keyboard.keyboardPress(arrowKey);
                await wait(100);
            }
        }
    });
const ActionPinchParamSchema = z.object({
    locate: getMidsceneLocationSchema().optional().describe('The element to pinch on. If not specified, the center of the screen will be used'),
    direction: z["enum"]([
        'in',
        'out'
    ]).describe('Pinch direction. "in" = pinch fingers together (zoom out / shrink), "out" = spread fingers apart (zoom in / enlarge).'),
    distance: z.number().positive().optional().describe('How far each finger moves in pixels. Defaults to a quarter of the shorter screen dimension.'),
    duration: z.number().default(500).optional().describe('Duration of the pinch gesture in milliseconds')
});
const defineActionPinch = (config)=>{
    if (!config.pinch) return;
    return defineAction({
        name: 'Pinch',
        description: 'Perform a two-finger pinch gesture. Use direction "in" to pinch fingers together (zoom out), or "out" to spread fingers apart (zoom in). Optionally specify distance for how far each finger moves.',
        interfaceAlias: 'aiPinch',
        paramSchema: ActionPinchParamSchema,
        sample: {
            locate: {
                prompt: 'the map area'
            },
            direction: 'out',
            distance: 200
        },
        call: async (param)=>{
            const { centerX, centerY, startDistance, endDistance, duration } = normalizePinchParam(param, await config.size());
            await config.pinch?.({
                x: centerX,
                y: centerY
            }, {
                startDistance,
                endDistance,
                duration
            });
        }
    });
};
function normalizePinchParam(param, screenSize) {
    const { width, height } = screenSize;
    const element = param.locate;
    const centerX = element ? Math.round(element.center[0]) : Math.round(width / 2);
    const centerY = element ? Math.round(element.center[1]) : Math.round(height / 2);
    const duration = param.duration ?? 500;
    const baseDistance = Math.round(Math.min(width, height) / 4);
    const fingerDistance = param.distance ?? baseDistance;
    const startDistance = baseDistance;
    const endDistance = 'out' === param.direction ? baseDistance + fingerDistance : Math.max(10, baseDistance - fingerDistance);
    return {
        centerX,
        centerY,
        startDistance,
        endDistance,
        duration
    };
}
function defineSystemInputAction(config, call) {
    return defineAction({
        name: config.name,
        description: config.description,
        interfaceAlias: config.interfaceAlias,
        delayBeforeRunner: config.delayBeforeRunner,
        delayAfterRunner: config.delayAfterRunner,
        call
    });
}
function defineActionsFromInputPrimitives(input, options = {}) {
    const actions = [];
    const { pointer, keyboard, scroll, touch, system } = input;
    if (pointer) {
        actions.push(defineActionTap(pointer.tap));
        if (pointer.doubleClick) actions.push(defineActionDoubleClick(pointer.doubleClick));
        if (pointer.rightClick) actions.push(defineActionRightClick(pointer.rightClick));
        if (pointer.hover) actions.push(defineActionHover(pointer.hover));
        if (pointer.dragAndDrop) actions.push(defineActionDragAndDrop(pointer.dragAndDrop));
        if (pointer.longPress) actions.push(defineActionLongPress(pointer.longPress));
    }
    if (keyboard) actions.push(defineActionInput(keyboard), defineActionClearInput(keyboard.clearInput), defineActionKeyboardPress(keyboard.keyboardPress), defineActionCursorMove({
        keyboard,
        sleep: options.sleep
    }));
    if (scroll) actions.push(defineActionScroll(scroll.scroll));
    if (touch?.swipe && options.size && false !== options.includeSwipe) actions.push(defineActionSwipe({
        swipe: touch.swipe,
        size: options.size
    }));
    if (touch?.pinch && options.size && false !== options.includePinch) actions.push(defineActionPinch({
        pinch: touch.pinch,
        size: options.size
    }));
    if (system && options.systemActions) {
        const { systemActions } = options;
        if (system.backButton && systemActions.backButton) actions.push(defineSystemInputAction(systemActions.backButton, system.backButton));
        if (system.homeButton && systemActions.homeButton) actions.push(defineSystemInputAction(systemActions.homeButton, system.homeButton));
        if (system.recentAppsButton && systemActions.recentAppsButton) actions.push(defineSystemInputAction(systemActions.recentAppsButton, system.recentAppsButton));
    }
    return actions.filter((action)=>Boolean(action));
}
function createDefaultMobileActions(context) {
    return defineActionsFromInputPrimitives(context.input, {
        size: context.size,
        sleep: context.sleep,
        systemActions: context.systemActions
    });
}
const ActionSleepParamSchema = z.object({
    timeMs: z.number().default(1000).optional().describe('Sleep duration in milliseconds, defaults to 1000ms (1 second)')
});
const defineActionSleep = ()=>defineAction({
        name: 'Sleep',
        description: 'Wait for a specified duration before continuing. Defaults to 1 second (1000ms) if not specified.',
        paramSchema: ActionSleepParamSchema,
        sample: {
            timeMs: 2000
        },
        call: async (param)=>{
            const duration = param?.timeMs ?? 1000;
            getDebug('device:common-action')(`Sleeping for ${duration}ms`);
            await new Promise((resolve)=>setTimeout(resolve, duration));
        }
    });
export { AbstractInterface, ActionLongPressParamSchema, ActionPinchParamSchema, ActionSleepParamSchema, ActionSwipeParamSchema, actionClearInputParamSchema, actionCursorMoveParamSchema, actionDoubleClickParamSchema, actionDragAndDropParamSchema, actionHoverParamSchema, actionInputParamSchema, actionKeyboardPressParamSchema, actionRightClickParamSchema, actionScrollParamSchema, actionTapParamSchema, createDefaultMobileActions, defineAction, defineActionClearInput, defineActionCursorMove, defineActionDoubleClick, defineActionDragAndDrop, defineActionHover, defineActionInput, defineActionKeyboardPress, defineActionLongPress, defineActionPinch, defineActionRightClick, defineActionScroll, defineActionSleep, defineActionSwipe, defineActionTap, defineActionsFromInputPrimitives, normalizeMobileSwipeParam, normalizePinchParam };

//# sourceMappingURL=index.mjs.map