#!/usr/bin/env node
/**
 * CLI entry point for codefree-o-ui.
 *
 * This script is the main entry point when users run `codefree-o-ui`
 * from the command line. It starts the Express server and optionally
 * opens the UI in the default browser.
 *
 * @module server/cli
 */

import { spawn } from 'child_process';
import path from 'path';
import { fileURLToPath } from 'url';

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

const args = process.argv.slice(2);
const openBrowser = !args.includes('--no-open');

async function openUrl(url) {
  const platform = process.platform;
  let command;
  if (platform === 'darwin') {
    command = 'open';
  } else if (platform === 'win32') {
    command = 'cmd';
    const args_for_open = ['/c', 'start', '""', url];
    spawn(command, args_for_open, { stdio: 'ignore' });
    return;
  } else {
    command = 'xdg-open';
  }
  spawn(command, [url], { stdio: 'ignore' });
}

async function main() {
  const { startServer } = await import('./index.js');

  const originalListen = import.meta.url;

  if (openBrowser) {
    const port = process.env.SERVER_PORT || 3001;
    setTimeout(() => {
      openUrl(`http://localhost:${port}`);
    }, 1500);
  }

  await import('./index.js');
}

main().catch((err) => {
  console.error('[CLI] Failed to start:', err.message);
  process.exit(1);
});
