import { app, BrowserWindow, ipcMain } from 'electron';
import * as path from 'path';
import * as os from 'os';
import { loadSeedConfig } from './config_loader';
import { fetchFullConfig } from './api_client';
import { registerShellHandlers } from './shell_handlers';
import { registerFileHandlers } from './file_handlers';
import { registerSystemHandlers } from './system_handlers';
import { SeedConfig } from '../shared/types';

let mainWindow: BrowserWindow | null = null;
let cachedSeed: SeedConfig | null = null;
let cachedFullConfig: any = null;

async function createWindow() {
  cachedSeed = await loadSeedConfig();
  if (cachedSeed) {
    cachedFullConfig = await fetchFullConfig(cachedSeed);
  }

  mainWindow = new BrowserWindow({
    width: 1600,
    height: 900,
    title: 'OSIT Aether Launcher (Native)',
    webPreferences: {
      preload: path.join(__dirname, '../preload/index.js'),
      contextIsolation: true,
      nodeIntegration: false,
    },
  });

  let targetUrl = 'http://demo.localhost:5173';
  if (cachedFullConfig && cachedFullConfig.native_device) {
    const device = cachedFullConfig.native_device;
    const eventId = device.event_id_random || device.event_id;
    const locationId = device.event_location_id_random || device.event_location_id || '';
    // Use app_base_url from the device record (e.g. bgh.oneskyit.com).
    // Fall back to localhost only if nothing is configured — never override a real domain.
    const host = device.app_base_url || 'demo.localhost:5173';
    // Use https for real domains; localhost dev URLs stay on http
    const protocol = host.includes('localhost') ? 'http' : 'https';
    targetUrl = `${protocol}://${host}/events/${eventId}/launcher/${locationId}`;
  }

  // Only open DevTools in development (not in a packaged .app build)
  if (!app.isPackaged) mainWindow.webContents.openDevTools();
  mainWindow.loadURL(targetUrl).catch(() => {
    mainWindow?.loadURL('https://dev-demo.oneskyit.com/');
  });

  mainWindow.on('closed', () => { mainWindow = null; });
}

registerShellHandlers();
registerFileHandlers();
registerSystemHandlers();

app.on('ready', createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

app.on('activate', () => {
  if (mainWindow === null) createWindow();
});

ipcMain.handle('get-seed-config', async () => cachedSeed || await loadSeedConfig());
ipcMain.handle('get-device-config', async () => cachedFullConfig);
ipcMain.handle('get-jwt', async () => null);

ipcMain.handle('get-device-info', async () => {
  const interfaces = os.networkInterfaces();
  const addresses: string[] = [];
  for (const name of Object.keys(interfaces)) {
    for (const net of interfaces[name]!) {
      if (net.family === 'IPv4' && !net.internal) {
        addresses.push(net.address);
      }
    }
  }
  return {
    platform: os.platform(),
    release: os.release(),
    arch: os.arch(),
    hostname: os.hostname(),
    cpus: os.cpus().length,
    total_mem: os.totalmem(),
    free_mem: os.freemem(),
    ip_addresses: addresses,
    home_directory: os.homedir(),
    tmp_directory: os.tmpdir()
  };
});
