import node_os from "node:os";
import node_path from "node:path";
import { ComputerDevice, agentFromComputer, checkAccessibilityPermission } from "@midscene/computer";
import { playgroundForAgentFactory } from "@midscene/playground";
import { PLAYGROUND_SERVER_PORT } from "@midscene/shared/constants";
import { findAvailablePort } from "@midscene/shared/node";
import puppeteer from "puppeteer";
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 = node_path.join(__dirname, '../../static');
const main = async ()=>{
    try {
        const accessibilityCheck = checkAccessibilityPermission(true);
        if (!accessibilityCheck.hasPermission) {
            console.error('❌ Permission Error:\n');
            console.error(accessibilityCheck.error);
            process.exit(1);
        }
        const displays = await 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 findAvailablePort(PLAYGROUND_SERVER_PORT);
        if (availablePort !== PLAYGROUND_SERVER_PORT) console.log(`⚠️  Port ${PLAYGROUND_SERVER_PORT} is busy, using port ${availablePort} instead`);
        const { server: playgroundServer } = await playgroundForAgentFactory(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 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 = node_path.join(node_os.homedir(), '.midscene', 'computer-playground');
        console.log(`💾 User data directory: ${userDataDir}`);
        const browser = await puppeteer.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();
