/**
 * FreeBSD-focused detection utilities for Clawdie setup.
 */
import { execSync } from 'child_process';
import os from 'os';

export type Platform = 'freebsd' | 'unknown';
export type ServiceManager = 'freebsd-rc' | 'none';

export function getPlatform(): Platform {
  return os.platform() === 'freebsd' ? 'freebsd' : 'unknown';
}

export function isRoot(): boolean {
  return process.getuid?.() === 0;
}

export function isHeadless(): boolean {
  return !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY;
}

/**
 * Open a URL or file path in the default browser.
 * FreeBSD commonly exposes xdg-open from desktop utilities.
 */
export function openBrowser(target: string): boolean {
  if (!commandExists('xdg-open')) return false;
  try {
    execSync(`xdg-open ${JSON.stringify(target)}`, { stdio: 'ignore' });
    return true;
  } catch {
    return false;
  }
}

export function getServiceManager(): ServiceManager {
  return getPlatform() === 'freebsd' ? 'freebsd-rc' : 'none';
}

export function getNodePath(): string {
  try {
    return execSync('command -v node', { encoding: 'utf-8' }).trim();
  } catch {
    return process.execPath;
  }
}

export function commandExists(name: string): boolean {
  try {
    execSync(`command -v ${name}`, { stdio: 'ignore' });
    return true;
  } catch {
    return false;
  }
}

export function getNodeVersion(): string | null {
  try {
    const version = execSync('node --version', { encoding: 'utf-8' }).trim();
    return version.replace(/^v/, '');
  } catch {
    return process.version ? process.version.replace(/^v/, '') : null;
  }
}

export function getNodeMajorVersion(): number | null {
  const version = getNodeVersion();
  if (!version) return null;
  const major = parseInt(version.split('.')[0], 10);
  return isNaN(major) ? null : major;
}
