const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
const configManager = app.isPackaged
    ? require(path.join(app.getAppPath(), 'src', 'config-manager'))
    : require('../src/config-manager');
const fs = require('fs');

// Initialize logging
const logDir = path.join(app.getPath('home'), '.ollie-hub');
const logPath = path.join(logDir, 'ollie-hub-launch.log');

function log(msg) {
    const timestamp = new Date().toISOString();
    try {
        if (!fs.existsSync(logDir)) {
            fs.mkdirSync(logDir, { recursive: true });
        }
        fs.appendFileSync(logPath, `[${timestamp}] ${msg}\n`);
    } catch(e) {
        console.error('Failed to write log:', e);
    }
}

log('Hub starting (main.js reached)');

const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
    app.quit();
    process.exit(0);
}

let mainWindow;
let serverInstance = null;

function getServerModule() {
    const isDev = !app.isPackaged;
    const appPath = app.getAppPath();
    if (isDev) {
        return require(path.join(appPath, '..', 'src', 'server.js'));
    } else {
        return require(path.join(appPath, 'src', 'server.js'));
    }
}

async function startServer() {
    try {
        const serverModule = getServerModule();
        if (serverModule && typeof serverModule.listen === 'function') {
            return new Promise((resolve, reject) => {
                serverInstance = serverModule.listen(process.env.PORT || configManager.getPort(), () => {
                    resolve(serverInstance);
                });
            });
        }
    } catch (error) {
        console.error('Failed to start server:', error);
    }
}

function createWindow() {
    mainWindow = new BrowserWindow({
        width: 750,
        height: 550,
        minWidth: 600,
        minHeight: 400,
        title: "Hub",
        backgroundColor: '#1E1E1E',
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            preload: path.join(__dirname, 'preload.js')
        }
    });

    // Remove menu bar for a cleaner widget look
    mainWindow.setMenuBarVisibility(false);

    mainWindow.loadURL(`http://localhost:${process.env.PORT || configManager.getPort()}`);
    if (!app.isPackaged) {
        // Only open dev tools if needed during dev, commented below for clean look
        // mainWindow.webContents.openDevTools({ mode: 'detach' });
    }
}

ipcMain.on('hub:close-window', () => {
    if (mainWindow) {
        mainWindow.close();
    }
});

app.whenReady().then(async () => {
    await startServer();
    // No OLLIE_HEADLESS guard: each Ollie app opens its own native
    // window wherever it runs. The host WM draws the chrome — AppKit
    // on macOS, DWM on Windows, KWin on Ollie System, whatever the user
    // has on other Linux distros. Standalone-app builds therefore
    // look native everywhere; on Ollie System the Breeze/Ollie chrome
    // makes them look identical to every other app.
    createWindow();
});

app.on('window-all-closed', () => {
    if (serverInstance) serverInstance.close();
    app.quit();
});
