"use strict";
var __webpack_require__ = {};
(()=>{
    __webpack_require__.n = (module)=>{
        var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
        __webpack_require__.d(getter, {
            a: getter
        });
        return getter;
    };
})();
(()=>{
    __webpack_require__.d = (exports1, definition)=>{
        for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
            enumerable: true,
            get: definition[key]
        });
    };
})();
(()=>{
    __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
})();
(()=>{
    __webpack_require__.r = (exports1)=>{
        if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
            value: 'Module'
        });
        Object.defineProperty(exports1, '__esModule', {
            value: true
        });
    };
})();
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
    BrowserWindowController: ()=>BrowserWindowController,
    computerPlaygroundPlatform: ()=>computerPlaygroundPlatform
});
const external_node_path_namespaceObject = require("node:path");
var external_node_path_default = /*#__PURE__*/ __webpack_require__.n(external_node_path_namespaceObject);
const computer_namespaceObject = require("@midscene/computer");
const playground_namespaceObject = require("@midscene/playground");
const constants_namespaceObject = require("@midscene/shared/constants");
const node_namespaceObject = require("@midscene/shared/node");
const computerPlaygroundPlatform = (0, playground_namespaceObject.definePlaygroundPlatform)({
    id: 'computer',
    title: 'Midscene Computer Playground',
    description: "Computer playground platform descriptor",
    async prepare (options) {
        const initialAccessibility = (0, computer_namespaceObject.checkAccessibilityPermission)(true);
        const initialScreenRecording = (0, computer_namespaceObject.checkScreenRecordingPermission)(true);
        const evaluatePermissions = ()=>{
            const accessibilityCheck = (0, computer_namespaceObject.checkAccessibilityPermission)(false);
            const screenRecordingCheck = (0, computer_namespaceObject.checkScreenRecordingPermission)(false);
            const permissionError = !accessibilityCheck.hasPermission && accessibilityCheck.error || !screenRecordingCheck.hasPermission && screenRecordingCheck.error || void 0;
            return {
                accessibilityCheck,
                screenRecordingCheck,
                permissionError,
                allPermissionsGranted: accessibilityCheck.hasPermission && screenRecordingCheck.hasPermission
            };
        };
        const staticDir = options?.staticDir || external_node_path_default().join(__dirname, '../../static');
        const availablePort = await (0, node_namespaceObject.findAvailablePort)(constants_namespaceObject.PLAYGROUND_SERVER_PORT);
        if (availablePort !== constants_namespaceObject.PLAYGROUND_SERVER_PORT) console.log(`⚠️  Port ${constants_namespaceObject.PLAYGROUND_SERVER_PORT} is busy, using port ${availablePort} instead`);
        const sessionManager = {
            async getSetupSchema () {
                const { allPermissionsGranted, permissionError } = evaluatePermissions();
                const displays = await (0, computer_namespaceObject.getConnectedDisplays)();
                const defaultDisplay = displays.find((display)=>display.primary) || displays[0];
                return {
                    title: 'Connect Computer Agent',
                    description: allPermissionsGranted ? 'Create a Computer Agent for the selected display.' : permissionError,
                    primaryActionLabel: 'Create Agent',
                    fields: [
                        {
                            key: 'displayId',
                            label: 'Display',
                            type: 'select',
                            required: true,
                            options: displays.map((display)=>({
                                    label: display.name,
                                    value: String(display.id),
                                    description: display.primary ? 'Primary display' : void 0
                                })),
                            defaultValue: defaultDisplay ? String(defaultDisplay.id) : '',
                            placeholder: 'Select a display'
                        }
                    ],
                    targets: displays.map((display)=>({
                            id: String(display.id),
                            label: display.name,
                            description: display.primary ? 'Primary display' : void 0,
                            isDefault: display.primary
                        }))
                };
            },
            async listTargets () {
                const displays = await (0, computer_namespaceObject.getConnectedDisplays)();
                return displays.map((display)=>({
                        id: String(display.id),
                        label: display.name,
                        description: display.primary ? 'Primary display' : void 0,
                        isDefault: display.primary
                    }));
            },
            async createSession (input) {
                const { allPermissionsGranted, permissionError } = evaluatePermissions();
                if (!allPermissionsGranted) throw new Error(permissionError || 'Accessibility and Screen Recording permissions are required');
                const displayId = input?.displayId === void 0 || null === input.displayId ? void 0 : String(input.displayId);
                const agent = await (0, computer_namespaceObject.agentFromComputer)(displayId ? {
                    displayId
                } : void 0);
                const displays = await (0, computer_namespaceObject.getConnectedDisplays)();
                const selectedDisplay = displays.find((display)=>display.id === displayId) || displays.find((display)=>display.primary) || displays[0];
                return {
                    agent,
                    agentFactory: ()=>(0, computer_namespaceObject.agentFromComputer)(selectedDisplay ? {
                            displayId: selectedDisplay.id
                        } : void 0),
                    preview: (0, playground_namespaceObject.createScreenshotPreviewDescriptor)({
                        title: 'Desktop preview'
                    }),
                    displayName: selectedDisplay?.name || 'Desktop',
                    metadata: {
                        displayId: selectedDisplay?.id,
                        executionUx: 'countdown-before-run'
                    }
                };
            }
        };
        return {
            platformId: 'computer',
            title: 'Midscene Computer Playground',
            sessionManager,
            launchOptions: {
                port: availablePort,
                openBrowser: false,
                verbose: false,
                staticPath: staticDir
            },
            executionHooks: {
                async beforeExecute () {
                    const windowController = options?.getWindowController?.();
                    if (!windowController) return void console.warn('⚠️  Window controller not initialized yet, skipping window control');
                    await new Promise((resolve)=>setTimeout(resolve, 1500));
                    await windowController.minimize();
                },
                async afterExecute () {
                    const windowController = options?.getWindowController?.();
                    if (!windowController) return;
                    await windowController.restore();
                }
            },
            preview: (0, playground_namespaceObject.createScreenshotPreviewDescriptor)({
                title: 'Desktop preview'
            }),
            metadata: {
                executionUx: 'countdown-before-run',
                sessionConnected: false,
                setupState: initialAccessibility.hasPermission && initialScreenRecording.hasPermission ? 'required' : 'blocked',
                setupBlockingReason: !initialAccessibility.hasPermission && initialAccessibility.error || !initialScreenRecording.hasPermission && initialScreenRecording.error || void 0
            }
        };
    }
});
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 BrowserWindowController {
    async minimize() {
        try {
            await this.session.send('Browser.setWindowBounds', {
                windowId: this.windowId,
                bounds: {
                    windowState: 'minimized'
                }
            });
            console.log('🔽 Window minimized, starting task execution...');
        } catch (error) {
            console.warn('⚠️  Failed to minimize window:', error);
        }
    }
    async restore() {
        try {
            await Promise.all([
                this.session.send('Browser.setWindowBounds', {
                    windowId: this.windowId,
                    bounds: {
                        windowState: 'normal'
                    }
                }),
                this.page.bringToFront()
            ]);
            console.log('🔼 Window restored');
        } catch (error) {
            console.warn('⚠️  Failed to restore window:', error);
        }
    }
    constructor(session, page, windowId){
        _define_property(this, "session", void 0);
        _define_property(this, "page", void 0);
        _define_property(this, "windowId", void 0);
        this.session = session;
        this.page = page;
        this.windowId = windowId;
    }
}
exports.BrowserWindowController = __webpack_exports__.BrowserWindowController;
exports.computerPlaygroundPlatform = __webpack_exports__.computerPlaygroundPlatform;
for(var __rspack_i in __webpack_exports__)if (-1 === [
    "BrowserWindowController",
    "computerPlaygroundPlatform"
].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
Object.defineProperty(exports, '__esModule', {
    value: true
});
