import type { ServerConfig } from '../types';
import { looksLikeXMRWallet } from './forgeValidation';

export interface SetupStatus {
  needsCalibration: boolean;
  reasons: string[];
}

function isBlankOrLocalPublicUrl(url: string | undefined): boolean {
  const u = (url ?? '').trim();
  if (!u) return true;
  try {
    const host = new URL(u).hostname.toLowerCase();
    return host === 'localhost' || host === '127.0.0.1' || host === '::1';
  } catch {
    return true;
  }
}

/** True when wallet or LAN public URL still need Calibrate before forging. */
export function getSetupStatus(config: ServerConfig | null | undefined): SetupStatus {
  if (!config) {
    return { needsCalibration: true, reasons: ['Server configuration not loaded'] };
  }
  const reasons: string[] = [];
  const wallet = config.wallet?.address?.trim() ?? '';
  if (!wallet) {
    reasons.push('Fleet payout wallet is empty');
  } else if (!looksLikeXMRWallet(wallet)) {
    reasons.push('Fleet payout wallet format looks invalid (expected Monero mainnet address)');
  }
  if (isBlankOrLocalPublicUrl(config.server?.public_url)) {
    reasons.push('Public URL is blank or localhost — set your LAN address in Calibrate');
  }
  return { needsCalibration: reasons.length > 0, reasons };
}

export function isSetupComplete(config: ServerConfig | null | undefined): boolean {
  return !getSetupStatus(config).needsCalibration;
}
