const os = require('os');
const { getLocalRuntimeModel } = require('../src/config/local-runtime-models');

function normalizeMemoryGb(bytes) {
  return Math.max(1, Math.round(bytes / (1024 ** 3)));
}

function getMachineProfile() {
  return {
    platform: process.platform,
    arch: process.arch,
    totalMemoryGb: normalizeMemoryGb(os.totalmem()),
    cpuCount: os.cpus().length
  };
}

function getOllamaRecommendedChatModel(profile = getMachineProfile()) {
  if (profile.totalMemoryGb <= 8) return 'qwen2.5:3b';
  if (profile.totalMemoryGb <= 16) return 'gemma3:4b';
  return 'llama3.1:8b';
}

function getEmbeddedRuntimeRecommendation(profile = getMachineProfile()) {
  const isAppleSilicon = profile.platform === 'darwin' && profile.arch === 'arm64';

  if (isAppleSilicon) {
    const model = getLocalRuntimeModel(profile.totalMemoryGb <= 16 ? 'qwen2.5-3b-instruct-4bit' : 'gemma-3-4b-it-4bit');
    return {
      supported: true,
      preferred: true,
      runtime: 'orgboard-runtime',
      engine: 'mlx-lm',
      modelSlug: model.slug,
      huggingFaceRepo: model.huggingFaceRepo,
      label: model.label,
      summary: 'Best local-first path for Apple Silicon. Fast startup, no Ollama dependency, direct model download from the app.'
    };
  }

  return {
    supported: false,
    preferred: false,
    runtime: 'orgboard-runtime',
    engine: profile.platform === 'darwin' ? 'llama.cpp' : 'llama.cpp',
    modelSlug: 'qwen2.5-3b-instruct-4bit',
    label: 'Qwen 2.5 3B Instruct 4-bit',
    summary: 'Planned embedded runtime for this machine class. Until then, use Ollama for local inference.'
  };
}

function getPreferredLocalRuntime(profile = getMachineProfile()) {
  const embedded = getEmbeddedRuntimeRecommendation(profile);
  return embedded.supported ? 'embedded' : 'ollama';
}

module.exports = {
  getMachineProfile,
  getOllamaRecommendedChatModel,
  getEmbeddedRuntimeRecommendation,
  getPreferredLocalRuntime
};
