import { spawn } from "node:child_process";
import { PLAYGROUND_SERVER_PORT } from "@midscene/shared/constants";
import cors from "cors";
import server_0 from "./server.mjs";
const LOOPBACK_HOSTS = new Set([
    'localhost',
    '127.0.0.1',
    '::1',
    '[::1]'
]);
function isLoopbackOrigin(origin) {
    if (!origin) return true;
    try {
        const url = new URL(origin);
        return LOOPBACK_HOSTS.has(url.hostname);
    } catch  {
        return false;
    }
}
function createDefaultCorsOptions() {
    return {
        origin (origin, callback) {
            callback(null, isLoopbackOrigin(origin));
        },
        credentials: true
    };
}
function createPlaygroundLauncher(agentOrFactory) {
    return {
        async launch (options = {}) {
            const { port = PLAYGROUND_SERVER_PORT, openBrowser = true, browserCommand, verbose = true, id, enableCors = false, staticPath, configureServer, corsOptions = createDefaultCorsOptions() } = options;
            if ('function' != typeof agentOrFactory && !agentOrFactory.interface) throw new Error('Agent must have an interface property');
            if (verbose) {
                console.log('🚀 Starting Midscene Playground...');
                if ('function' == typeof agentOrFactory) console.log('📱 Agent: factory');
                else {
                    console.log(`📱 Agent: ${agentOrFactory.constructor.name}`);
                    console.log(`🖥️ Page: ${agentOrFactory.interface.constructor.name}`);
                }
                console.log(`🌐 Port: ${port}`);
                if (staticPath) console.log(`📁 Static path: ${staticPath}`);
                if (enableCors) console.log('🔓 CORS enabled');
            }
            const server = new server_0(agentOrFactory, staticPath, id);
            if (enableCors) server.app.use(cors(corsOptions));
            if (configureServer) await configureServer(server);
            const launchedServer = await server.launch(port);
            if (verbose) console.log(`✅ Playground server started on port ${port}`);
            const url = `http://127.0.0.1:${port}`;
            if (openBrowser) await openInBrowser(url, browserCommand, verbose);
            return {
                server: launchedServer,
                port,
                host: '127.0.0.1',
                close: async ()=>{
                    if (verbose) console.log('🛑 Shutting down Midscene Playground...');
                    try {
                        await launchedServer.close();
                        if (verbose) console.log('✅ Playground shutdown complete');
                    } catch (error) {
                        if (verbose) console.error('❌ Error during playground shutdown:', error);
                        throw error;
                    }
                }
            };
        }
    };
}
function playgroundForAgent(agent) {
    return createPlaygroundLauncher(agent);
}
function playgroundForAgentFactory(agentFactory) {
    return createPlaygroundLauncher(agentFactory);
}
async function openInBrowser(url, customCommand, verbose = true) {
    return new Promise((resolve, reject)=>{
        let command;
        let args;
        if (customCommand) {
            command = customCommand;
            args = [
                url
            ];
        } else switch(process.platform){
            case 'darwin':
                command = 'open';
                args = [
                    url
                ];
                break;
            case 'win32':
                command = 'start';
                args = [
                    '',
                    url
                ];
                break;
            default:
                command = 'xdg-open';
                args = [
                    url
                ];
                break;
        }
        if (verbose) console.log(`🌐 Opening browser: ${command} ${args.join(' ')}`);
        const child = spawn(command, args, {
            detached: true,
            stdio: 'ignore'
        });
        child.on('error', (error)=>{
            if (verbose) {
                console.warn('⚠️  Failed to open browser automatically:', error.message);
                console.log(`🌐 Please open manually: ${url}`);
            }
            resolve();
        });
        child.on('close', ()=>{
            resolve();
        });
        child.unref();
    });
}
export { playgroundForAgent, playgroundForAgentFactory };

//# sourceMappingURL=launcher.mjs.map