import { loadConfig } from '../config.js';

/**
 * Open the observer dashboard in the default browser.
 *
 * If SHADE_OBSERVER_URL is set, uses that. Otherwise derives it from
 * SHADE_PREKEY_SERVER assuming the observer is mounted on the same host.
 */
export async function dashboardCommand(): Promise<void> {
  const config = loadConfig();

  const baseUrl = config.observerUrl ?? `${config.prekeyServer}/shade-observer`;
  const dashboardUrl = `${baseUrl.replace(/\/$/, '')}/dashboard/`;

  console.log(`Opening ${dashboardUrl}`);
  if (config.observerToken) {
    console.log(`Token is configured — paste it on the login screen.`);
  } else {
    console.log(`No SHADE_OBSERVER_TOKEN set — you'll be prompted to enter it in the browser.`);
  }

  // Open in default browser (cross-platform)
  const platform = process.platform;
  const opener = platform === 'darwin' ? 'open' : platform === 'win32' ? 'start' : 'xdg-open';
  try {
    Bun.spawn([opener, dashboardUrl], { stdout: 'ignore', stderr: 'ignore' });
  } catch {
    console.log(`Failed to auto-open. Copy the URL above into your browser.`);
  }
}
