/**
 * Lazy `sharp` load so a corrupt/missing native install does not crash Electron at import time.
 * Call only from image-processing paths; errors are recoverable for the rest of the app.
 *
 * Note: main is bundled to CJS (esbuild). `import.meta.url` is empty there — prefer `__filename`.
 */
import { createRequire } from 'node:module';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

/**
 * @returns {string}
 */
function requireBaseFilename() {
  // CJS bundle / Electron main
  if (typeof __filename === 'string' && __filename.length > 0) {
    return __filename;
  }
  // Direct ESM (unit tests)
  const metaUrl = import.meta.url;
  if (typeof metaUrl === 'string' && metaUrl.startsWith('file:')) {
    return fileURLToPath(metaUrl);
  }
  return path.join(process.cwd(), 'package.json');
}

const require = createRequire(requireBaseFilename());

/** @type {typeof import('sharp') | null} */
let cached = null;
/** @type {Error | null} */
let loadError = null;

/**
 * @param {unknown} err
 * @returns {Error}
 */
export function sharpLoadFailure(err) {
  const detail = err instanceof Error ? err.message : String(err);
  return new Error(
    [
      'Не удалось загрузить модуль обработки изображений (sharp).',
      'Переустановите приложение полностью (удалите и поставьте заново)',
      'или исключите папку установки из проверки антивируса.',
      detail ? `Детали: ${detail}` : '',
    ]
      .filter(Boolean)
      .join(' '),
  );
}

/**
 * @returns {typeof import('sharp')}
 */
export function getSharp() {
  if (cached) return cached;
  if (loadError) throw loadError;
  try {
    cached = require('sharp');
    return cached;
  } catch (err) {
    loadError = sharpLoadFailure(err);
    throw loadError;
  }
}

/** Reset cache (tests only). */
export function __resetSharpRuntimeForTests() {
  cached = null;
  loadError = null;
}
