"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BackendManager = void 0;
const electron_1 = require("electron");
const events_1 = require("events");
const path = __importStar(require("path"));
const tsyringe_1 = require("tsyringe");
/**
 * BackendManager
 *
 * Manages utility processes for app backends.
 * Each app's backend code runs in an isolated utility process.
 * Uses Electron's utilityProcess for better main process integration
 * and MessageChannelMain for direct frontend<->backend communication.
 */
let BackendManager = class BackendManager extends events_1.EventEmitter {
    backends = new Map();
    backendData = new Map();
    /**
     * MessagePort pairs for frontend<->backend communication
     * The BackendManager holds references to the main-process side of ports
     */
    backendPorts = new Map();
    /**
     * Create and start a utility process for an app backend
     */
    async createBackend(appId, manifest, installPath, launchArgs) {
        // Check if backend already exists
        if (this.backends.has(appId)) {
            throw new Error(`Backend for app ${appId} already exists`);
        }
        // Check if app has a backend
        const backendConfig = manifest.backend;
        if (!backendConfig?.entry) {
            throw new Error(`App ${appId} does not have a backend`);
        }
        const backendEntryPath = path.join(installPath, backendConfig.entry);
        // Path to the backend runtime that wraps the actual backend
        const runtimePath = path.join(__dirname, "../../app-runtime/backend-preload.js");
        // Create utility process with the runtime as entry point
        const backend = electron_1.utilityProcess.fork(runtimePath, [`--launch-args=${JSON.stringify(launchArgs || [])}`], {
            serviceName: `eden-backend-${appId}`,
            env: {
                ...process.env,
                EDEN_APP_ID: appId,
                EDEN_BACKEND_ENTRY: backendEntryPath,
                EDEN_INSTALL_PATH: installPath,
                EDEN_MANIFEST: JSON.stringify(manifest),
            },
        });
        // Only create frontend<->backend MessageChannel if app has a frontend
        const hasFrontend = !!manifest.frontend?.entry;
        if (hasFrontend) {
            // Create MessageChannel for frontend<->backend communication
            const { port1, port2 } = new electron_1.MessageChannelMain();
            // port1 goes to the backend (utility process)
            // port2 goes to the frontend (will be transferred via IPCBridge)
            backend.postMessage({ type: "init-port" }, [port1]);
            // Store port2 for later transfer to frontend
            this.backendPorts.set(appId, port2);
        }
        // Set up backend event handlers
        backend.on("message", (message) => {
            this.handleBackendMessage(appId, message);
        });
        backend.on("exit", (code) => {
            console.log(`Backend for app ${appId} exited with code ${code}`);
            this.backends.delete(appId);
            this.backendData.delete(appId);
            this.backendPorts.delete(appId);
            this.emit("backend-exit", { appId, code });
        });
        // Register backend early so it can receive responses to shell commands
        // during initialization (before backend-ready is sent)
        this.backends.set(appId, backend);
        this.backendData.set(appId, { manifest, installPath });
        // Wait for the backend to signal it's ready
        try {
            await new Promise((resolve, reject) => {
                const timeout = setTimeout(() => {
                    reject(new Error(`Backend ${appId} startup timed out after 10 seconds`));
                }, 10000);
                const onMessage = (msg) => {
                    if (msg.type === "backend-ready") {
                        clearTimeout(timeout);
                        backend.removeListener("message", onMessage);
                        resolve();
                    }
                    else if (msg.type === "backend-error") {
                        clearTimeout(timeout);
                        backend.removeListener("message", onMessage);
                        reject(new Error(msg.error));
                    }
                };
                backend.on("message", onMessage);
            });
        }
        catch (error) {
            // Clean up on failure
            this.backends.delete(appId);
            this.backendData.delete(appId);
            this.backendPorts.delete(appId);
            throw error;
        }
        console.log(`Backend started for app ${appId}${hasFrontend ? " (with frontend port)" : " (backend-only)"}`);
        return { backend };
    }
    /**
     * Send a message to a backend's utility process (for IPC from main)
     */
    sendMessage(appId, message) {
        const backend = this.backends.get(appId);
        if (!backend) {
            console.warn(`No backend found for app ${appId}`);
            return false;
        }
        try {
            console.log(`Sending message to backend ${appId}:`, message.type);
            backend.postMessage(message);
            return true;
        }
        catch (error) {
            console.error(`Failed to send message to backend ${appId}:`, error);
            return false;
        }
    }
    /**
     * Send a message with ports to a backend's utility process
     */
    sendPortToBackend(appId, message, ports) {
        const backend = this.backends.get(appId);
        if (!backend) {
            console.warn(`No backend found for app ${appId}`);
            return false;
        }
        try {
            console.log(`Sending message with ${ports.length} ports to backend ${appId}:`, message.type);
            backend.postMessage(message, ports);
            return true;
        }
        catch (error) {
            console.error(`Failed to send message with ports to backend ${appId}:`, error);
            return false;
        }
    }
    /**
     * Get the frontend port for an app (to transfer to renderer)
     */
    getFrontendPort(appId) {
        return this.backendPorts.get(appId);
    }
    /**
     * Terminate a backend utility process
     */
    async terminateBackend(appId) {
        const backend = this.backends.get(appId);
        if (!backend) {
            console.warn(`No backend found for app ${appId}`);
            return;
        }
        try {
            // Create a promise that resolves when backend exits
            const exitPromise = new Promise((resolve) => {
                backend.once("exit", () => {
                    resolve();
                });
            });
            // Create a timeout promise (5 seconds)
            const timeoutPromise = new Promise((_, reject) => {
                setTimeout(() => {
                    reject(new Error(`Backend ${appId} termination timed out after 5 seconds`));
                }, 5000);
            });
            // Send graceful shutdown message first
            backend.postMessage({ type: "shutdown" });
            // Wait a bit for graceful shutdown
            await new Promise((resolve) => setTimeout(resolve, 500));
            // Kill if still running
            if (this.backends.has(appId)) {
                backend.kill();
            }
            // Wait for either exit or timeout
            await Promise.race([exitPromise, timeoutPromise]);
            this.backends.delete(appId);
            this.backendData.delete(appId);
            // Close the port
            const port = this.backendPorts.get(appId);
            if (port) {
                port.close();
                this.backendPorts.delete(appId);
            }
        }
        catch (error) {
            console.error(`Failed to terminate backend ${appId}:`, error);
            // Force cleanup even on error
            this.backends.delete(appId);
            this.backendData.delete(appId);
            this.backendPorts.delete(appId);
            throw error;
        }
    }
    /**
     * Get backend by app ID
     */
    getBackend(appId) {
        return this.backends.get(appId);
    }
    /**
     * Check if backend exists for app
     */
    hasBackend(appId) {
        return this.backends.has(appId);
    }
    /**
     * Get all running backend IDs
     */
    getRunningBackends() {
        return Array.from(this.backends.keys());
    }
    /**
     * Handle messages from backends (for system-level IPC)
     */
    handleBackendMessage(appId, message) {
        // Emit event for IPC bridge to handle
        this.emit("backend-message", {
            appId,
            message,
        });
    }
    /**
     * Terminate all backends
     */
    async terminateAll() {
        const terminationPromises = Array.from(this.backends.keys()).map((appId) => this.terminateBackend(appId));
        await Promise.all(terminationPromises);
    }
};
exports.BackendManager = BackendManager;
exports.BackendManager = BackendManager = __decorate([
    (0, tsyringe_1.singleton)(),
    (0, tsyringe_1.injectable)()
], BackendManager);
//# sourceMappingURL=BackendManager.js.map