import fs from 'node:fs';
import path from 'node:path';

import { app, nativeImage, type NativeImage } from 'electron';
import Logger from 'electron-log/main';

/**
 * Resolve the app icon without the electron-vite `?asset` pipeline
 * (that emits into out/main/chunks/, which electron-builder excludes).
 *
 * Packaged Linux builds also put a copy at resources/icon.png via extraResources.
 */
export const resolveAppIconPath = (): string | undefined => {
	const appPath = app.getAppPath();
	const candidates = [
		// electron-builder extraResources
		path.join(process.resourcesPath, 'icon.png'),
		path.join(appPath, 'build', 'icon.png'),
		path.join(
			appPath.replace(/app\.asar$/, 'app.asar.unpacked'),
			'build',
			'icon.png'
		),
		path.join(process.resourcesPath, 'app.asar.unpacked', 'build', 'icon.png'),
		// electron-vite / repo checkout: out/main -> ../../build/icon.png
		path.join(__dirname, '../../build/icon.png'),
		path.join(__dirname, '../../../build/icon.png')
	];

	for (const p of candidates) {
		try {
			if (fs.existsSync(p)) return p;
		} catch {
			/* ignore */
		}
	}
	Logger.warn(
		'App icon not found. Checked:\n' + candidates.map(c => `  ${c}`).join('\n')
	);
	return undefined;
};

export const loadAppIcon = (): NativeImage | undefined => {
	const p = resolveAppIconPath();
	if (!p) return undefined;
	const img = nativeImage.createFromPath(p);
	if (img.isEmpty()) {
		Logger.warn(`App icon at ${p} loaded empty`);
		return undefined;
	}
	return img;
};
