import { app, BrowserWindow } from 'electron'
import path from 'path'
import { spawn } from 'child_process'
import { fileURLToPath } from 'url'

const __dirname = path.dirname(fileURLToPath(import.meta.url))

let pyProc = null

function getResourcePath() {
  // Whether run via dev mode or system pacman package,
  // electron.js is inside frontend/, and src/ is next to it.
  return path.join(__dirname, '..');
}

function createServer() {
  const resourcePath = getResourcePath();
  const scriptPath = path.join(resourcePath, 'src', 'server.py')
  
  // Rely on system Python 3 as specified in PKGBUILD dependencies
  const pythonPath = 'python3'
  
  // Forward CLI arguments (e.g., --search or --install) to the Python backend
  const args = [scriptPath, ...process.argv.slice(1)]
  
  pyProc = spawn(pythonPath, args, {
    cwd: resourcePath
  })
  
  pyProc.stdout.on('data', (data) => console.log(data.toString()))
  pyProc.stderr.on('data', (data) => console.error(data.toString()))
}

function createApp() {
  const splash = new BrowserWindow({
    width: 300,
    height: 300,
    minWidth: 300,
    minHeight: 300,
    maxWidth: 300,
    maxHeight: 300,
    frame: false,
    transparent: true,
    alwaysOnTop: true,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    }
  });

  splash.loadFile(path.join(__dirname, 'splash.html'));

  createServer();

  const win = new BrowserWindow({
    width: 900,
    height: 700,
    minWidth: 888,
    minHeight: 450,
    title: 'Stratum',
    show: false,
    autoHideMenuBar: true,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    }
  })

  // Always load index.html for vanilla web components
  win.loadFile(path.join(__dirname, 'index.html'))
  win.setMenu(null) // Completely remove the menu bar

  // Wait a moment for flask to start, then swap windows
  setTimeout(() => {
    splash.close()
    win.show()
  }, 2000)
}

app.whenReady().then(() => {
  createApp()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createApp()
    }
  })
})

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