"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);
})();
var __webpack_exports__ = {};
const external_node_os_namespaceObject = require("node:os");
var external_node_os_default = /*#__PURE__*/ __webpack_require__.n(external_node_os_namespaceObject);
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 external_puppeteer_namespaceObject = require("puppeteer");
var external_puppeteer_default = /*#__PURE__*/ __webpack_require__.n(external_puppeteer_namespaceObject);
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;
    }
}
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
            }
        };
    }
});
const bin_staticDir = external_node_path_default().join(__dirname, '../../static');
const main = async ()=>{
    try {
        const displays = await computer_namespaceObject.ComputerDevice.listDisplays();
        if (displays.length > 0) {
            console.log('🖥️  Available displays:');
            for (const display of displays)console.log(`  ${display.primary ? '✅' : '  '} ${display.name} (${display.id})${display.primary ? ' [Primary]' : ''}`);
        }
        let windowController = null;
        console.log('🚀 Starting server...');
        const prepared = await computerPlaygroundPlatform.prepare({
            staticDir: bin_staticDir,
            getWindowController: ()=>windowController
        });
        const { server: playgroundServer } = await (0, playground_namespaceObject.launchPreparedPlaygroundPlatform)(prepared);
        console.log('');
        console.log('✨ Midscene Computer Playground is ready!');
        console.log(`🎮 Playground: http://localhost:${playgroundServer.port}`);
        console.log(`🔑 Server ID: ${playgroundServer.id}`);
        console.log('');
        const url = `http://localhost:${playgroundServer.port}`;
        console.log('🌐 Launching browser in standalone window mode...');
        const device = new computer_namespaceObject.ComputerDevice();
        await device.connect();
        const screenSize = await device.size();
        await device.destroy();
        const windowWidth = 500;
        const maxWindowHeight = 1200;
        const windowHeight = Math.min(screenSize.height, maxWindowHeight);
        console.log(`📐 Screen size: ${screenSize.width}x${screenSize.height}, window size: ${windowWidth}x${windowHeight}`);
        const userDataDir = external_node_path_default().join(external_node_os_default().homedir(), '.midscene', 'computer-playground');
        console.log(`💾 User data directory: ${userDataDir}`);
        const browser = await external_puppeteer_default().launch({
            headless: false,
            defaultViewport: null,
            userDataDir,
            args: [
                `--app=${url}`,
                `--window-size=${windowWidth},${windowHeight}`,
                '--no-first-run',
                '--no-default-browser-check'
            ]
        });
        console.log('✅ Browser launched successfully');
        const pages = await browser.pages();
        const page = pages[0];
        const session = await page.createCDPSession();
        const windowInfo = await session.send('Browser.getWindowForTarget');
        console.log(`🪟 Window ID: ${windowInfo.windowId}`);
        windowController = new BrowserWindowController(session, page, windowInfo.windowId);
        console.log('✅ Window controller initialized');
        process.on('SIGINT', async ()=>{
            console.log('\n👋 Shutting down...');
            await browser.close();
            process.exit(0);
        });
    } catch (error) {
        console.error('❌ Failed to start server:', error);
        process.exit(1);
    }
};
main();
for(var __rspack_i in __webpack_exports__)exports[__rspack_i] = __webpack_exports__[__rspack_i];
Object.defineProperty(exports, '__esModule', {
    value: true
});
