import { app, shell, BrowserWindow } from "electron";
import { setupLiveHandlers } from "./ipc/live";
import { setupWorkflowHandlers } from "./ipc/workflow";
import { preload, indexHtml, ELECTRON_RENDERER_URL } from "./config";

// 必须在 app ready 之前调用
app.commandLine.appendSwitch("disable-site-isolation-trials");

app.commandLine.appendSwitch(
    "disable-features",
    "IsolateOrigins,site-per-process",
);

// 简单的开发环境检测
const isDev = process.env.NODE_ENV === "development";

/**
 * 创建主窗口
 */
function createWindow(): void {
    const mainWindow = new BrowserWindow({
        width: 1080,
        height: 670,
        show: false,
        titleBarStyle: "hidden",
        autoHideMenuBar: true,
        webPreferences: {
            preload,
            sandbox: false,
        },
    });

    mainWindow.on("ready-to-show", () => {
        mainWindow.show();
    });

    mainWindow.webContents.openDevTools();

    mainWindow.webContents.setWindowOpenHandler((details) => {
        shell.openExternal(details.url);
        return { action: "deny" };
    });

    // 窗口关闭时强制清理资源并退出应用
    mainWindow.on("closed", () => {
        // 清理所有资源
        mainWindow.removeAllListeners();
        // 强制退出应用
        if (process.platform !== "darwin") {
            app.quit();
        }
    });

    if (isDev && ELECTRON_RENDERER_URL) {
        mainWindow.loadURL(ELECTRON_RENDERER_URL);
    } else {
        mainWindow.loadFile(indexHtml);
    }
}

/**
 * 准备好后
 */
app.whenReady().then(() => {
    app.setAppUserModelId("com.electron");

    // 直播相关处理
    setupLiveHandlers();

    setupWorkflowHandlers();

    createWindow();

    app.on("activate", function () {
        if (BrowserWindow.getAllWindows().length === 0) createWindow();
    });
});

/**
 * 退出应用
 */
app.on("window-all-closed", () => {
    // 强制清理所有资源
    if (process.platform !== "darwin") {
        app.quit();
    }
});

// 在开发环境中，确保进程正确退出
app.on("before-quit", () => {
    // 清理所有资源
    const windows = BrowserWindow.getAllWindows();
    windows.forEach((window) => {
        window.removeAllListeners();
        window.close();
    });
});

// 处理进程退出信号
process.on("SIGINT", () => {
    app.quit();
});

process.on("SIGTERM", () => {
    app.quit();
});
