"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 constants_namespaceObject = require("@midscene/shared/constants");
const node_namespaceObject = require("@midscene/shared/node");
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 staticDir = external_node_path_default().join(__dirname, '../../static');
const main = async ()=>{
    try {
        const accessibilityCheck = (0, computer_namespaceObject.checkAccessibilityPermission)(true);
        if (!accessibilityCheck.hasPermission) {
            console.error('❌ Permission Error:\n');
            console.error(accessibilityCheck.error);
            process.exit(1);
        }
        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 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 { server: playgroundServer } = await (0, playground_namespaceObject.playgroundForAgentFactory)(computer_namespaceObject.agentFromComputer).launch({
            port: availablePort,
            openBrowser: false,
            verbose: false,
            staticPath: staticDir,
            configureServer (server) {
                server.app.use('/execute', async (_req, res, next)=>{
                    if (!windowController) {
                        console.warn('⚠️  Window controller not initialized yet, skipping window control');
                        next();
                        return;
                    }
                    await new Promise((resolve)=>setTimeout(resolve, 1500));
                    await windowController.minimize();
                    const originalSend = res.send.bind(res);
                    res.send = (body)=>{
                        windowController?.restore();
                        return originalSend(body);
                    };
                    next();
                });
            }
        });
        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
});
