const fs = require("fs");
const os = require("os");
const path = require("path");

function getLinuxAppIdentity(appId) {
    const id = `io.stillhq.swai.${appId}`;

    return {
        id,
        // MPRIS org.mpris.MediaPlayer2.DesktopEntry is the desktop-file ID
        // without the .desktop suffix. GNOME uses it to resolve the app icon.
        desktopName: id,
    };
}

function getDesktopSearchDirectories() {
    const dataHome = process.env.XDG_DATA_HOME
        || path.join(os.homedir(), ".local", "share");
    const dataDirs = (process.env.XDG_DATA_DIRS || "/usr/local/share:/usr/share")
        .split(":")
        .filter(Boolean);
    return [dataHome, ...dataDirs].map((dir) => path.join(dir, "applications"));
}

function findInstalledIcon(appId) {
    const { desktopName } = getLinuxAppIdentity(appId);
    for (const directory of getDesktopSearchDirectories()) {
        const desktopFile = path.join(directory, `${desktopName}.desktop`);
        try {
            const match = fs.readFileSync(desktopFile, "utf8").match(/^Icon=(.+)$/m);
            if (!match) continue;
            const icon = match[1].trim();
            if (path.isAbsolute(icon) && fs.existsSync(icon)) return icon;
        } catch (error) {
            if (error.code !== "ENOENT") {
                console.warn(`Failed to read desktop entry ${desktopFile}:`, error.message);
            }
        }
    }
    return null;
}

module.exports = { findInstalledIcon, getLinuxAppIdentity };
